Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
haskell中列表理解的If-else_Haskell_List Comprehension - Fatal编程技术网

haskell中列表理解的If-else

haskell中列表理解的If-else,haskell,list-comprehension,Haskell,List Comprehension,我正在写一个代码,它有一个if-else和列表理解,它是允许的,如果不是,我怎么能写这个代码 valid :: [(String, Int)]-> [String]-> [(String, Int)] vaild dict words = [if checks word dict then (word, scores word)|word <- words ] valid::[(字符串,Int)]->[String]->[(字符串,In

我正在写一个代码,它有一个if-else和列表理解,它是允许的,如果不是,我怎么能写这个代码

valid :: [(String, Int)]-> [String]-> [(String, Int)]
vaild dict words = [if checks word dict
                    then (word, scores word)|word <- words ]
valid::[(字符串,Int)]->[String]->[(字符串,Int)]
有效dict words=[如果检查单词dict

然后(单词,分数单词)|单词我不明白你为什么被否决。正如对你问题的评论所说,你可能想要这样的东西:

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

valid :: [(String, Int)]-> [String]-> [(String, Int)]
valid dict = map (id &&& scores) . filter (flip checks dict)
可以进一步简化如下:

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

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

在Haskell中,所有东西都有一个类型,对吗?所以
如果检查单词dict,那么…
有一个特定的类型, 在这个例子中,
(String,Int)
。想象一下,如果
检查单词dict
为false,我们仍然需要生成
(String,Int)
类型的东西,那么我们到底能做些什么呢

为了避免这种明显的困境,Haskell总是需要一个
else
子句。将
if-then-else
看作类似于C的
foo?bar:baz
(三元运算符)更准确

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

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

[(word,scores-word)| word我想您只需要字典中存在的单词列表。因此您需要枚举部分的条件:
[(word,scores-word)|Haskell中的单词在
if…then…else…
表达式中,
else
子句不是可选的。我也不知道为什么这是被否决的。我已经投票反对rep更改。对我来说,这似乎是一个非常好的初学者问题