1

I need to implement a split function in haskell where user gives the as a example input

splitx [1,2,3,4,5,6] 3 

should output -> [1,2,3]

splitx::[Int]->Int->[Int]
splitx [] 0 = []
splitx (x:xs) n = x: splitx xs (n-1)

i wrote the following function but it gives a error

Non-exhaustive patterns in function Main.splitx

just tell me where am i wrong ?

1
  • does you function return the first n elements? is that a requirement? Commented Jul 9, 2011 at 8:13

4 Answers 4

2

What should splitx [] n be? And how does the computer know that?

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

1 Comment

good point.. well, with the current code it is undefined, which matches the specification :)
1

If you want to return the first n elements:

you have no pattern match for input where n=0 and list is not empty:

splitx _ 0 = []

Note: specify the type to be generic so it works not only with Ints:

splitx :: [a] -> Int -> [a]

4 Comments

yet its returns be the full list :-o
While your solution is correct, the explanation is not! The only missing pattern is splitx [] n where n is not equal to zero. The pattern splitx _ 0 is matched by splitx (x:xs) n.
You are right. What I wanted to say is that it's matched but shouldn't be, because you want to terminate at that point.
@Rotsor @yi_H thanks for the answers . my problem is always i only consider about the main pattern matching thiggy :-s
1

The error (actually warning, i believe) that you are receiving is complaining that the pattern matches (on the left side of the =) are not exhaustive. You need to add an extra case for the situation where you get [] and n as arguments.

2 Comments

By following this suggestion one will get a specialisation of const :)
Derp, I was going on 36 hours without sleep when I wrote my original answer. I've corrected my answer by removing my code examples.
1

Now that your original question is answered, do you have to use recursion and pattern matching for your homework? If not, you'll notice that splitx is a lot like take with reversed arguments:

GOA> let splitx = flip take
GOA> splitx [1,2,3,4,5,6] 3
[1,2,3]
GOA> splitx [1,2,3,4,5,6] 0
[]
GOA> splitx [] 3
[]
GOA> splitx "abcde" 3
"abc"

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.