2017-07-28 59 views
0

我在Haskell很新。我想实现拆分功能,它将列表分成两部分:Haskell:分割函数出错

split 2 [1,2,3] → ([1,2], [3]) --means the first part has length 2, the second - length x-2 
split 2 [1] → ([1], []) 


split :: Int -> [a] -> ([a],[a]) 
split 0 x = ([], x) 
split n x = splitH n x [] 

splitH :: Int -> [a] -> [a] -> ([a], [a]) 
splitH n (x:xs) begin | n == 0 = (begin, xs) 
         | otherwise = splitH n-1 xs (x:begin) -- here is the error 

    main = print(split 2 [1,2,3]) 

但是,此代码不能编译。我得到一个错误

`Couldn't match expected type ‘([a], [a])’ 
      with actual type ‘[a0] -> [a0] -> ([a0], [a0])’ 
Relevant bindings include 
    begin :: [a] (bound at jdoodle.hs:6:17) 
    xs :: [a] (bound at jdoodle.hs:6:13) 
    x :: a (bound at jdoodle.hs:6:11) 
    splitH :: Int -> [a] -> [a] -> ([a], [a]) (bound at jdoodle.hs:6:1) 
Probable cause: ‘splitH’ is applied to too few arguments 
In the first argument of ‘(-)’, namely ‘splitH n’ 
In the expression: splitH n - 1 xs (x : begin)` 

什么可能导致错误?周围的表达n-1

+0

为了便于比较,您可以查看['splitAt']的标准实现(https://hackage.haskell.org/package/base-4.10.0.0/docs/src/GHC.List.html# splitAt) – ephemient

回答

3

认沽括号:

splitH (n-1) xs (x:begin) 

一下第7,“功能应用的优先级高于运营商”的this article一个解释:

所以,如果你看到这样的事情:

fabc + gde

您知道您正在添加两个函数调用的结果,而不是调用一个函数,其中一个参数是两个项的总和。