为什么Haskell抱怨这个加号?

问题描述 投票:-2回答:3

从这个代码旨在将平衡的三元表示转换为Haskell Integer

frombal3 :: String -> Integer
frombal3 "+" =  1
frombal3 "0" =  0
frombal3 "-" = -1
frombal3 current:therest = \
  (*) frombal3 current (^) 3 length therest \
  + frombal3 therest

我收到了错误:

main.hs:7:3: error: parse error on input ‘+’
  |
7 |   + frombal3 therest
  |   ^
<interactive>:3:1: error:
   • Variable not in scope: main
   • Perhaps you meant ‘min’ (imported from Prelude)
haskell
3个回答
3
投票

目前尚不清楚你想要实现什么,但我可以看到一些已经指出的错误。

Problems

你不需要\来继续一行,这只需要在字符串内部。在Haskell中缩进就足够了

您需要将模式与括号匹配:(current:therest)。此外,此模式将使current成为Char而不是String,因此您无法直接将其传递给带有String的函数。

你还需要包装你的函数参数:如果你想将frombal3 current乘以3,你需要(*) (frombal3 current) 3,或者更好的frombal3 current * 3。中缀函数具有更高的优先级,使代码更清晰。

Suggestions

我不确定你想要实现什么,但这看起来像是可以通过fold或简单列表理解来完成的


1
投票

不要使用反斜杠,并记住正确支持模式匹配:

frombal3 :: String -> Integer
frombal3 "+" =  1
frombal3 "0" =  0
frombal3 "-" = -1
frombal3 (current:therest) = -- ^ Note brackets
  (*) frombal3 current (^) 3 length therest 
  + frombal3 therest

由于您使用运算符的方式,这仍然会导致问题,但我认为您可以自己解决这个问题,特别是因为我无法弄清楚您在这里尝试做什么。


1
投票

你似乎试图使用反斜杠继续下一行;不要那样做。如果您只是删除所有反斜杠,错误将消失。 (你会得到其他几个错误,但这个错误会消失。)

Haskell使用缩进来检测一个部分结束和下一个部分开始的位置。您不需要手动将反斜杠添加到每行的末尾以继续表达式。

© www.soinside.com 2019 - 2024. All rights reserved.