Haskell:将列表理解为组合式 [英] Haskell: List Comprehension to Combinatory
问题描述
受到此文章的启发.我正在将翻译功能从列表理解转换为组合样式.我发现了一些有趣的东西.
Inspired by this article. I was playing with translating functions from list comprehension to combinatory style. I found something interesting.
-- Example 1: List Comprehension
*Main> [x|(x:_)<-["hi","hello",""]]
"hh"
-- Example 2: Combinatory
*Main> map head ["hi","hello",""]
"hh*** Exception: Prelude.head: empty list
-- Example 3: List Comprehension (translated from Example 2)
*Main> [head xs|xs<-["hi","hello",""]]
"hh*** Exception: Prelude.head: empty list
示例1没有引发异常似乎很奇怪,因为(x:_)
模式与head
的定义之一匹配.使用列表推导时是否暗含filter (not . null)
?
It seems strange that example 1 does not throw an exception, because (x:_)
pattern matches one of the definitions of head
. Is there an implied filter (not . null)
when using list comprehensions?
推荐答案
请参阅有关列表理解的部分在Haskell报告中.所以基本上
See the section on list comprehensions in the Haskell report. So basically
[x|(x:_)<-["hi","hello",""]]
被翻译为
let ok (x:_) = [ x ]
ok _ = [ ]
in concatMap ok ["hi","hello",""]
P.S.由于列表解析可以转换为do
表达式,因此do
表达式也会发生类似的事情,如
P.S. Since list comprehensions can be translated into do
expressions, a similar thing happens with do
expressions, as detailed in the section on do expressions. So the following will also produce the same result:
do (x:_)<-["hi","hello",""]
return x
这篇关于Haskell:将列表理解为组合式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!