首页 > 解决方案 > 有没有更简单的方法来编写这个函数并且只使用 Haskell 的前奏?

问题描述

所以我对 Haskell 很陌生,并且正在尝试解决一个任务,我已经解决了,但我想知道是否有更简单或更漂亮的方法来使函数与我的wordChange. 我试图只使用前奏中的内容。

dictionaryChecker _ [] = False
dictionaryChecker word (x:xs) = if elem word (snd x) then True else dictionaryChecker word xs

wordChange :: String -> String 
wordChange str = unwords (map (\s -> if length (translate s) > 0 then (translate s) 
else if (dictionaryChecker s dictionary) then concat (replicate (length s) "*")
else s) (words str))

translate :: String -> String 
translate str = contains str dictionary

contains _ [] = ""
contains str (x:xs) = if elem str (snd x) then fst x else contains str xs

标签: haskell

解决方案


我建议使用lookupfrom 函数Prelude,它接受一个键和一个元组列表(又名字典)并返回Maybe value. 这大大简化了您的功能。此外,如果 changeWord 使用字典,它应该是显式的,而不是使用全局变量。下面是部分解决方案:因为这是一项任务,我认为您应该尝试完成它;)

changeWord :: [(String, String)] -> String -> String
changeWord dic s = unwords $ substitute ws
  where -- ws is just the list of words s has  
        ws = words s
        -- the function substitute does the word changing recursively. Try to complete it
        substitute []     = []
        substitute (x:xs) = 
         case lookup x dic of -- look for x in the dictionary and returns the value if found
           Nothing -> undefined --complete
           Just y  -> undefined --complete

推荐阅读