haskell 在Hashkell绑定中使用where或let时出现语法错误

hts6caw3  于 2022-12-23  发布在  其他
关注(0)|答案(1)|浏览(120)

我最近才接触到Haskell世界。但是,仍然在语法上挣扎。后面的两个方法都有语法错误。问题可能是什么?版本1:

rev' :: [a] -> [a]
rev' [] = []
rev' [x] = [x]
rev' (x:xs) = let revHelper acc l = 
                    | acc [] = []
                    | revHelper acc (x':l') = revHelper (x':acc) l'
              in revHelper [] (x:xs)

第二版:

rev' :: [a] -> [a]
rev' [] = []
rev' [x] = [x]
rev' (x:xs) = revHelper [] (x:xs)
    where revHelper acc l = 
            | acc [] = []
            | revHelper acc (x':l') = revHelper (x':acc) l'

两者都有同样的问题:

util.hs:47:21: error: parse error on input ‘|’
   |
47 |                     | acc [] = []
   |

有人能帮帮我吗?
我正在尝试实现一个尾部递归反向函数。

kcwpcxri

kcwpcxri1#

您使用防护的方式不正确。您可能希望使用以下方式实现此问题:

rev' :: [a] -> [a]
rev' [] = []
rev' [x] = [x]
rev' (x:xs) = let revHelper acc [] = []
                  revHelper acc (x':l') = revHelper (x':acc) l'
              in revHelper [] (x:xs)

但这并不完全正确:您应该返回累加器,因此:

rev' :: [a] -> [a]
rev' [] = []
rev' [x] = [x]
rev' (x:xs) = let revHelper acc [] = acc
                  revHelper acc (x':l') = revHelper (x':acc) l'
              in revHelper [] (x:xs)

此外,这里没有必要定义rev'的基本情况,您可以将其实现为:

rev' :: [a] -> [a]
rev' = go []
    where go acc [] = acc
          go acc (x:xs) = go (x:acc) xs

相关问题