Home > Enterprise >  Trying to code my own 'partition' function in haskell
Trying to code my own 'partition' function in haskell

Time:01-05

as the title says, I'm trying to recode this function but I keep getting an error that says that the type that I output doesnt match the expected type. Could someone help me with this? Here's my code :

myPartition :: (a -> Bool) -> [a] -> ([a], [a])
myPartition f (x:xs) = if f x
    then (x : myPartition f xs, [])
    else ([], x : myPartition f xs)
myPartition _ [] = ([], [])

Also, im not authorized to use any function of the standard library

CodePudding user response:

The main problem is that your function checks if f x holds, and if so constructs a 2-tuple where it will write the entire result of the recursive call. That result will be a 2-tuple as well, so you try to use a 2-tuple as an element in a 2-tuple as an element in a …

You should make a recursive call to obtain a 2-tuple of elements for the rest of the list, and the prepend the item to any of the two, so:

myPartition :: (a -> Bool) -> [a] -> ([a], [a])
myPartition p = go
  where go (x:xs)
          | p x = (…, …)
          | otherwise = (…, …)
          where (pa, pb) = go xs
        go [] = ([], [])

where you still need to fill in the parts.

  • Related