2017-07-28 58 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

您知道您正在添加兩個函數調用的結果,而不是調用一個函數,其中一個參數是兩個項的總和。