如何在Haskell中无需导入Data.List等库实现单词翻译功能
你目前写的代码和单词翻译的需求完全不匹配,存在几个核心错误:
- 没有定义存储翻译对的字典结构,翻译对应该以
(原词, 译词)的形式存在列表里 - 逻辑中没有判断输入单词和字典中原词是否匹配的分支
- 不必要地使用了
do语法,该语法仅用于Monad上下文,纯函数的查找逻辑不需要用到
正确实现方案
1. 定义翻译字典
你可以自行扩充更多翻译条目,格式统一为(原单词, 目标语单词):
dictionary :: [(String, String)] dictionary = [("thanks", "danke"), ("hello", "hallo"), ("yes", "ja"), ("no", "nein")]
2. 实现翻译函数
完全不依赖任何外部库,通过自定义递归逻辑实现查找,函数类型符合要求的String -> String:
translate :: String -> String translate input = findTrans input dictionary where findTrans :: String -> [(String, String)] -> String -- 兜底逻辑:遍历完字典找不到匹配时返回原单词,可根据需求修改为其他返回值 findTrans w [] = w -- 逐个匹配字典条目 findTrans w ((origin, trans):remainDict) | w == origin = trans | otherwise = findTrans w remainDict
使用示例
- 调用
translate "thanks"得到结果"danke" - 调用
translate "hello"得到结果"hallo" - 调用
translate "test"找不到匹配返回原词"test"
内容的提问来源于stack exchange,提问作者thenord
相关产品推荐
相关产品推荐

