如何在这个实例中应用使用地图?

Sha*_*ane 3 haskell

我有一个月份和字符串列表.我想检查字符串中是否有任何月份.我还有一个函数,可以搜索字符串中的单词.我是否必须重写该功能,还是可以使用某种形式的地图?

fullMons = ["january", "febuary", "march", "april", "may", "june", "july", "september", "october", "november", "december"]

searchStrList :: String -> [String] -> Bool
searchStrList str strList = elem (map toLower str) $ convertToLower $ words strList
Run Code Online (Sandbox Code Playgroud)

我如何利用这些函数来做这样的事情:

check :: String -> Bool 
check str = searchStrList "january" || searchStrList "febuary" || ...
Run Code Online (Sandbox Code Playgroud)

仍然只是学习Haskell,所以对我的代码的任何其他评论表示赞赏.谢谢

ehi*_*ird 9

请注意,这fullMons不是一个函数而是一个列表,并且searchStrList不会键入; words采用单个字符串,但您将其应用于字符串列表.

我想你要做的是找出字符串中的单词是否包含任何月份名称fullMons.让我们尝试逐步推导出一个解决方案.我们要做的第一件事是应用于words我们的输入字符串; 这让我们得到了一个字符串列表.

words str :: [String]
Run Code Online (Sandbox Code Playgroud)

然后我们想知道是否有任何words s一个月份名称的元素.有一个功能any:

any :: (a -> Bool) -> [a] -> Bool
Run Code Online (Sandbox Code Playgroud)

所以,我们的解决方案应该如此

check str = any ??? (words str)
Run Code Online (Sandbox Code Playgroud)

而我们所要做的就是找出答案???.该elem函数让我们检查列表中的元素是否:

elem :: (Eq a) => a -> [a] -> Bool
Run Code Online (Sandbox Code Playgroud)

在这种情况下,列表应该是月份列表,我们要搜索的元素应该是字符串的单词.所以,填补空白:

check :: String -> Bool
check str = any (\word -> word `elem` fullMons) (words str)
Run Code Online (Sandbox Code Playgroud)

(注意:foo `op` bar只是op foo bar;很多操作符都是以这种方式编写和读取的.)

我们可以通过删除参数使这更简单,更惯用:

check :: String -> Bool
check = any (\word -> word `elem` fullMons) . words
Run Code Online (Sandbox Code Playgroud)

这意味着我们应用于words输入,然后应用于any (\word -> elem word fullMons)结果words.您可以进一步简化为:

check :: String -> Bool
check = any (`elem` fullMons) . words
Run Code Online (Sandbox Code Playgroud)

(即" words我们输入的任何元素都出现在fullMons?")

但这不是必要的.

我认为您试图获得的原始解决方案是依次检查整个字符串上的每个月的名称.要做到这一点,我们只需要稍微翻转一下控制结构:

check :: String -> Bool
check str = any (\word -> word `elem` ws) fullMons
  where ws = words str
Run Code Online (Sandbox Code Playgroud)

(即"做任何的元素fullMons出现在words str?")