我试着在一个函数中写3-4 where语句但是我得到错误并且无法做到,我试图做那样的事情:
foo x=
| x == foo1 = 5
| x == foo2 =3
| x == foo3 =1
| otherwise =2
where foo1= samplefunct1 x
foo2= samplefunct2 x
foo3= samplefunct3 x
我知道代码有点无用,但我只是写了这个来举例说明我的意思。
有没有人可以帮助我?提前谢谢。
答案 0 :(得分:22)
删除=
之后的foo x
并缩进代码,如
foo x
| x == foo1 = 5
| x == foo2 =3
| x == foo3 =1
| otherwise =2
where foo1 = samplefunct1 x
foo2 = samplefunct2 x
foo3 = samplefunct3 x
你没事。
答案 1 :(得分:9)
这段代码几乎是正确的,你只需要正确的缩进:空格在haskell中很重要。此外,在=
之后foo
使用警卫是一个错误,因此您也必须删除它。结果是:
foo x
| x == foo1 = 5
| x == foo2 =3
| x == foo3 =1
| otherwise =2
where foo1= whatever1 x
foo2= whatever2 x
foo3= whatever3 x
答案 2 :(得分:9)
如果你的缩进有点不均匀,就像这样:
foo x
| x == foo1 = 5
| x == foo2 =3
| x == foo3 =1
| otherwise =2
where foo1= samplefunct1 x
foo2= samplefunct2 x
foo3= samplefunct3 x
然后确实,错误消息谈到了意外的=
(并且将来,请在问题正文中包含完整的错误消息)。
您通过重新对齐或使用显式分隔符{ ; }
来修复此错误,使其对空格不敏感:
foo x
| x == foo1 = 5
| x == foo2 =3
| x == foo3 =1
| otherwise =2
where { foo1= samplefunct1 x ;
foo2= samplefunct2 x ;
foo3= samplefunct3 x }
这样运行正常(不是它是一个很好用的样式)。有时甚至看起来甚至对你来说都是如此,但如果有一些 制表符 隐藏在空白区域内,则不会。