在Haskell中是否有多个where语句的方法?

22

我尝试在一个函数中编写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

我知道这段代码有点没用,但我只是写了一个示例来说明我的意思。

有人能帮我吗?先谢谢了。


2
foo x 后面不应该有 = - gspr
1
@gspr,是的,你说得对,对不起,但我认为那不是真正的问题。 - caesar_
5
此外,我建议您将来在包含错误时进行说明。仅告诉他人您“遇到了错误”是没有建设性的。 - gspr
我会将您的编辑回滚到原始版本,因为答案是基于原始版本的。 :) - Will Ness
3个回答

38

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_
你确定你的空格符号是正确的吗?很难确定你所说的“像”我代码的意思。我粘贴的代码没有语法错误。 - gspr
哦,这种情况下,你的代码看起来可能与你上面粘贴的代码有很大不同。包括实际的代码可能会有所帮助。 - gspr
是的,我确定,我现在会发布我写的代码。你能检查一下它的 where 部分吗? - caesar_
当你的代码在注释中时,我无法检查空格/缩进。此外,您确定语法错误不是在代码的其他地方吗?您检查过行号了吗? - gspr

14

如果您的缩进有些不均匀,像这样:

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 }

这段代码虽然能正常运行(但不推荐使用这种写法),有时候看起来也没问题,但如果在空格中有一些制表符隐藏着,就会出现问题。


12

这段代码几乎正确,你只需要正确缩进:在 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

谢谢,但我想在每个where语句中使用3个不同的函数。正如您从我的代码中看到的,第一个where正在运行samplefunc1,第二个正在运行samplefunct2,以此类推,您确定这样做可以吗? - caesar_
1
是的,我只是使用了“id”以使其编译通过,无论您放什么都没有关系。 - daniel gratzer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接