Reputation: 91
I'm a new to haskell, I'm trying to create a function that will take a list on integers and returns a list containing two sublists, the first sublist containing the even number and the other containing the odd numbers. I cannot use even, odd or filter functions. i created my own functions as follows
myodd :: Integer -> Bool
myodd n = rem (abs(n)) 2 == 1
myeven :: Integer -> Bool
myeven n = rem (abs(n)) 2 == 0
segregate [] = ([], [])
segregate [x] = ([x], [])
segregate (x:y:xs) = (x:xp, y:yp) where (xp, yp) = segregate xs
im having trouble trying to use the two first functions and use it on the segregated functions. I have more experience in racket and the function I crated looks like this:
(define (myeven? x)
(= (modulo x 2) 0))
(define (myodd? x)
(= (modulo x 2) 1))
(define (segregate xs)
(foldr (lambda (x b)
(if (myeven? x)
(list (cons x (first b)) (second b))
(list (first b) (cons x (second b))))) '(()()) xs))
Upvotes: 0
Views: 641
Reputation: 36339
If you really need such a function rather than writing it for educational purposes, there is partition
in Data.List
, so a simple
import Data.List(partition)
wil get you going.
In the educational case, you can still compare your code, once you're done, with the code of partition
.
Upvotes: 0
Reputation: 17973
A simple way is to run through the list twice using each of your hand-rolled functions as a guard predicate:
segregate :: [Integer] -> ([Integer], [Integer])
segregate [] = ([],[])
segregate xs = (evens, odds)
where evens = [x | x <- xs, myeven x]
odds = [x | x <- xs, myodd x]
Note: your question asked for a list of lists but your pattern matching segregate [] = ([],[])
indicated you wanted a tuple so I gave a tuple solution.
Upvotes: 0
Reputation: 48631
Here's one good way:
segregate [] = ?
segregate (x:xs)
| myEven x = ?
| otherwise = ?
where (restEvens, restOdds) = segregate xs
You could also use
segregate = foldr go ([], []) where
go x ~(evens, odds)
| myEven x = ?
| otherwise = ?
Upvotes: 1