0

I am very new at Haskell. I want to implement split function, which splites a list into two parts:

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] )

But this code does not compile. I get an error

`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)`

What could cause the error ?

1
  • For comparison, you can look at the standard implementation of splitAt Commented Jul 28, 2017 at 2:00

1 Answer 1

3

Put parentheses around the expression n-1:

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

Look at section 7, "Function Application Has Precedence over Operators" of this article for an explanation:

So if you see something like this:

f a b c + g d e

you know that you are adding the result of two function calls rather than calling one function with one of the arguments being the sum of two terms.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.