解析守卫的错误

时间:2014-07-01 18:46:41

标签: parsing sorting haskell merge

我实现了合并排序的合并子程序。我在编译时收到此错误消息:输入|

上的解析错误
merge :: [Int] -> [Int] -> [Int]
merge xs ys = go xs ys []
    where go xs ys zs =
            |null ys              = zs ++ xs                     
            |null xs              = zs ++ ys                        
            |(head xs) <= head ys = go (tail xs) ys (head xs : zs)  
            |otherwise            = go xs (tail ys) (head ys : zs)

谁能告诉我为什么?还有更简洁的方法吗?谢谢。

1 个答案:

答案 0 :(得分:3)

您可以在=之后删除go xs ys zs来修复语法错误 - 在使用警卫定义某些内容时,=仅在每个警卫之后出现,就像您已经拥有的一样。

除此之外,如果你更多地使用模式匹配,你的代码会更加清晰。您可以使用模式null来识别空列表,并head来检查tail[],而不是检查列表是否为(x:xs)。识别非空列表并将头部和尾部绑定到名称xxs等:

merge :: [Int] -> [Int] -> [Int]
merge xs ys = go xs ys []
    where go xs [] zs          = zs ++ xs
          go [] ys zs          = zs ++ ys
          go (x:xs) (y:ys) zs
              | x <= y         = go xs (y:ys) (x:zs)
              | otherwise      = go (x:xs) ys (y:zs)