在Haskell中创建不带参数的函数时解析错误

时间:2019-04-19 18:33:21

标签: haskell

我正在尝试创建一个不带参数的函数,以创建列表推导。当我尝试运行代码时,出现解析错误,并且编译失败,我也不知道为什么。

我一直试图在终端上运行它,但是它不起作用。

这是我的代码:

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 ]
  |           ^^^^^^^^

1 个答案:

答案 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实例来编写列表,而是使用三元组构造函数(,,)来编写此代码,该构造函数可以消除样板变量xyz

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