在Haskell中创建没有参数的函数时解析错误

问题描述 投票:0回答:1

我正在尝试创建一个没有参数的函数来创建列表理解。当我尝试运行代码时,我得到一个解析错误,它无法编译,我不知道为什么。

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

这是我的代码:

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 ]
  |           ^^^^^^^^
haskell
1个回答
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实例为列表编写这个,使用3元组构造函数(,,),它可以省去样板变量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
© www.soinside.com 2019 - 2024. All rights reserved.