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

仅使用Haskell Prelude库,有没有更简洁的方式实现wordChange函数?

Haskell wordChange 函数优化实现

以下是仅使用Prelude库、更简洁易读的实现方案,适配你原有代码的字典结构(每个字典项为(替换目标词, [匹配同义词列表])):

wordChange :: String -> String
wordChange = unwords . map processWord . words
  where
    -- 单个单词的处理逻辑
    processWord s = case findMatch s dictionary of
      -- 匹配到可替换目标,直接返回目标词
      Just target -> target
      -- 未匹配到替换目标时,判断是否在字典中,是则打码,否则返回原词
      Nothing | s `isInDict` dictionary -> replicate (length s) '*'
              | otherwise -> s

    -- 查找单词对应的替换目标,找不到返回Nothing
    findMatch _ [] = Nothing
    findMatch s ((target, synonyms):rest)
      | s `elem` synonyms = Just target
      | otherwise = findMatch s rest

    -- 判断单词是否存在于字典的任意同义词列表中
    isInDict _ [] = False
    isInDict s ((_, synonyms):rest) = s `elem` synonyms || isInDict s rest

优化说明

  1. 消除重复遍历:原代码每个单词会遍历两次字典(一次查替换值、一次判断是否在字典中),优化后如果匹配到替换目标只会遍历一次字典,仅未匹配到替换目标时才会二次遍历。如果你原有代码的掩码分支实际不会触发(原代码中translate s非空和dictionaryChecker s dictionary为真的条件完全一致,掩码分支逻辑永远走不到),可以直接去掉isInDict判断,简化为如下版本:
wordChange :: String -> String
wordChange = unwords . map processWord . words
  where
    processWord s = maybe s id (findMatch s dictionary)
    findMatch _ [] = Nothing
    findMatch s ((t, syns):rest)
      | s `elem` syns = Just t
      | otherwise = findMatch s rest
  1. 提升可读性:
    • 用where子句收拢内部辅助逻辑,不需要对外暴露的函数不用定义为顶层函数
    • 用模式匹配替代多层嵌套的if判断,分支逻辑更直观
    • 用函数组合消去冗余的参数声明,主函数逻辑链条清晰(拆分单词→逐个处理→拼接成句)
    • 掩码生成简化为replicate (length s) '*',等价原有写法但更简洁
  2. 表意更清晰:辅助函数命名直接体现功能,避免无意义的命名。

内容的提问来源于stack exchange,提问作者SonCOR

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 14:18:05