Ohad
Ohad

Reputation: 1647

splitting a list of integers to 2 lists: one of positive numbers and the other of negative numbers - haskell

How can I split a list of integers to 2 lists: one of positive numbers and the other of negative numbers ?

this is my attempt:

is it possible to do it ?

split:: [Int]->[[Int]]
split [] =[[]]
split xs =[x|x<-xs, x<0]:[y|y<-xs, x>=0]

my second try:

split:: [Int]->([Int],[Int])
split [] =([],[])
split xs = ([x|x<-xs,x<0],[y|y<-xs,y>=0])

somehow I am still not getting the correct result.

when I run

   split [1,2-2,3-4]

I got

   ([-1],[1,0])   

Upvotes: 0

Views: 896

Answers (1)

Ganesh Sittampalam
Ganesh Sittampalam

Reputation: 29110

You can do this with the partition function:

import Data.List

split = partition (>=0)

Your attempt has a few problems. Firstly you need to parenthesise the x:xs pattern otherwise it will be parsed as (split x):xs which is not what you meant. Secondly, it will produce a type error because the : operator on the right-hand side should be given a single element as its left argument and a list of those elements as its right argument, but you have given it a list as both arguments. Finally since you only want to return two lists, you should use a tuple for the return type, not a nested list.

Upvotes: 3

Related Questions