我正在尝试创建一个没有参数的函数来创建列表理解。当我尝试运行代码时,我得到一个解析错误,它无法编译,我不知道为什么。
我一直试图在终端上运行它,但它不起作用。
这是我的代码:
outfits = let pants = ["jeans", "khaki", "leggings"]
shirts = ["white shirt", "grey turtleneck", "pink polo", "green hoodie"]
shoes = ["brogues", "converse", "sandals", "adidas"]
outfits1 = [ (x, y, z) | z <- pants, y <- shirts, x <- shoes ]
这是出现的错误:
warmup.hs:7:11: error: parse error on input ‘outfits1’
|
7 | outfits1 = [ (x, y, z) | z <- pants, y <- shirts, x <- shoes ]
| ^^^^^^^^
没有let
表达式,你只需写
outfits = [ (x, y, z) | z <- ["jeans", "khaki", "leggings"], y <- ["white shirt", "grey turtleneck", "pink polo", "green hoodie"], x <- ["brogues", "converse", "sandals", "adidas"] ]
let
表达式需要两个部分:紧跟在关键字let
之后的本地绑定,以及在关键字in
之后使用这些绑定的表达式:
outfits = let pants = ["jeans", "khaki", "leggings"]
shirts = ["white shirt", "grey turtleneck", "pink polo", "green hoodie"]
shoes = ["brogues", "converse", "sandals", "adidas"]
in [ (x, y, z) | z <- pants, y <- shirts, x <- shoes ]
或者,你可以使用where
子句来编写它,它将“main”表达式放在第一位:
outfits = [ (x, y, z) | z <- pants, y <- shirts, x <- shoes ]
where pants = ["jeans", "khaki", "leggings"]
shirts = ["white shirt", "grey turtleneck", "pink polo", "green hoodie"]
shoes = ["brogues", "converse", "sandals", "adidas"]
Applicative
而不是列表理解我会使用Applicative
实例为列表编写这个,使用3元组构造函数(,,)
,它可以省去样板变量x
,y
和z
。
outfits = (,,) <$> ["jeans", "khaki", "leggings"]
<*> ["white shirt", "grey turtleneck", "pink polo", "green hoodie"]
<*> ["brogues", "converse", "sandals", "adidas"]
您仍然可以使用let
表达式或where
子句为装备的每个组件提供名称:
outfits = let pants = ["jeans", "khaki", "leggings"]
shirts = ["white shirt", "grey turtleneck", "pink polo", "green hoodie"]
shoes = ["brogues", "converse", "sandals", "adidas"]
in (,,) <$> pants <*> shirts <*> shoes
要么
outfits = (,,) <$> pants <*> shirts <*> shoes
where pants = ["jeans", "khaki", "leggings"]
shirts = ["white shirt", "grey turtleneck", "pink polo", "green hoodie"]
shoes = ["brogues", "converse", "sandals", "adidas"]
如果... <$> ... <*> ... <*> ...
看起来太深奥,你可以给模式一个更具描述性的名称:
outfits = mixAndMatch pants shirts shoes
where pants = ["jeans", "khaki", "leggings"]
shirts = ["white shirt", "grey turtleneck", "pink polo", "green hoodie"]
shoes = ["brogues", "converse", "sandals", "adidas"]
mixAndMatch a b c = (,,) <$> a <*> b <*> c