繁体   English   中英

如果否则在haskell中使用列表理解

[英]If else with list comprehension in haskell

我正在编写一个代码,其中包含if else with list comprehension是否允许,如果没有,我怎么能写这段代码?

valid :: [(String, Int)]-> [String]-> [(String, Int)]
vaild dict words = [if checks word dict
                    then (word, scores word)|word <- words ]

其中check给出bool值

在Haskell中,一切都有类型吗? 因此, if checks word dict then ...具有特定类型,在这种情况下(String, Int) 想象一下,如果checks word dict是假的,我们仍然需要生成类型(String, Int)东西,那么我们到底能做什么呢?

为了避免这个明显的泥潭,Haskell总是需要一个else子句。 if then else像C的foo ? bar : baz那样, if then else更准确地想到if then else东西foo ? bar : baz foo ? bar : baz (三元运营商)。

然而,在列表理解中,有一个很好的解决方案。 你可以将谓词放在理解体中,以“保护”到达左侧的内容

[(word, scores word) | word <- words, checks word dict]

这基本上通过选择每个单词词words ,然后检查checks word dict ,如果返回false,我们“跳过”这个元素。

实际上有monad和MonadPlus ,但是我不会提到这个,因为我认为这只会让你感到困惑:)将它视为一点魔力是可以的。

我不明白为什么你被投票了。 正如你的问题的评论所述,你可能想要这样的东西:

valid :: [(String, Int)]-> [String]-> [(String, Int)]
valid dict words = [(word, scores word) | word <- words, checks word dict]

这非常类似于在Python中实现它的方式。

或者,您可以使用“do”表示法执行此操作:

import Control.Monad (guard)

valid :: [(String, Int)]-> [String]-> [(String, Int)]
valid dict words = do 
    word <- words
    guard (checks word dict)
    return (word, scores word)

或者,如果您根本不想使用列表推导,那么这样的事情会起作用:

import Control.Arrow

valid :: [(String, Int)]-> [String]-> [(String, Int)]
valid dict words = map (id &&& scores) $ filter (\word -> checks word dict) words

这可以进一步简化如下:

import Control.Arrow

valid :: [(String, Int)]-> [String]-> [(String, Int)]
valid dict = map (id &&& scores) . filter (flip checks dict)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM