我尝试在一个函数中编写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
一切都好。
=
)”,我的where语句部分如下:
|otherwise = (-1,-1)
where rightk = rightCheck area number
leftk = leftCheck area number当我删除其中一个where语句时,程序可以正常运行。 - caesar_如果您的缩进有些不均匀,像这样:
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 }
这段代码虽然能正常运行(但不推荐使用这种写法),有时候看起来也没问题,但如果在空格中有一些制表符隐藏着,就会出现问题。
这段代码几乎正确,你只需要正确缩进:在 Haskell 中,空格很重要。此外,在 guards 中使用 =
后面跟 foo
是错误的,所以你还需要将其删除。最终结果如下:
foo x
| x == foo1 = 5
| x == foo2 =3
| x == foo3 =1
| otherwise =2
where foo1= whatever1 x
foo2= whatever2 x
foo3= whatever3 x
foo x
后面不应该有=
。 - gspr