我正在尝试创建一个不带参数的函数,以创建列表推导。当我尝试运行代码时,出现解析错误,并且编译失败,我也不知道为什么。
我一直试图在终端上运行它,但是它不起作用。
这是我的代码:
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 ]
| ^^^^^^^^
答案 0 :(得分:7)
没有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
实例来编写列表,而是使用三元组构造函数(,,)
来编写此代码,该构造函数可以消除样板变量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