You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Haskell中无需导入Data.List等库实现单词翻译功能

你目前写的代码和单词翻译的需求完全不匹配,存在几个核心错误:

  1. 没有定义存储翻译对的字典结构,翻译对应该以(原词, 译词)的形式存在列表里
  2. 逻辑中没有判断输入单词和字典中原词是否匹配的分支
  3. 不必要地使用了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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 00:24:03