我试图在一个函数中编写 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
我知道代码有点没用,但我写这个只是为了举例说明我的意思。
有没有人可以帮助我?提前致谢。
我试图在一个函数中编写 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
我知道代码有点没用,但我写这个只是为了举例说明我的意思。
有没有人可以帮助我?提前致谢。
删除=
之后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
你很好。
If your indentation is a bit uneven, like this:
foo x
| x == foo1 = 5
| x == foo2 =3
| x == foo3 =1
| otherwise =2
where foo1= samplefunct1 x
foo2= samplefunct2 x
foo3= samplefunct3 x
then indeed, the error message talks about unexpected =
(and in the future, please do include full error message in the question body).
You fix this error by re-aligning, or with explicit separators { ; }
, making it white-space–insensitive:
foo x
| x == foo1 = 5
| x == foo2 =3
| x == foo3 =1
| otherwise =2
where { foo1= samplefunct1 x ;
foo2= samplefunct2 x ;
foo3= samplefunct3 x }
This runs fine (not that it is a nice style to use). Sometimes it even looks even to you, but isn't, if there are some tab characters hiding in the white-space.
这段代码几乎是正确的,你只需要正确的缩进:空格在 haskell 中很重要。此外,使用=
afterfoo
是守卫的错误,因此您也必须将其删除。结果是:
foo x
| x == foo1 = 5
| x == foo2 =3
| x == foo3 =1
| otherwise =2
where foo1= whatever1 x
foo2= whatever2 x
foo3= whatever3 x