Reputation: 51
I am trying to create a function in haskell that takes a predicate and a list as arguments and returns the prefix of the list satisfying the predicate.
the test being:
p1tests = [myTakeWhile (/= ' ') "This is practice." == "This"]
I have this so far..
myTakeWhile :: (a-> Bool ) -> [a] -> [a]
myTakeWhile [] =[]
myTakeWhile (x:xs)=[] : map (x:) (myTakeWhile xs)
I receive errors saying except type
Upvotes: 0
Views: 68
Reputation: 477160
You need to work with both the predicate and the elements in the list. The function thus should look like:
myTakeWhile :: (a -> Bool) -> [a] -> [a]
myTakeWhile _ [] = []
myTakeWhile p (x:xs)
| p x = …
| otherwise = …
where the p x
guard thus covers the case where the predicate is satisfied for the first item of the list, and the otherwise
is not.
In case the predicate is satisfied, we have to yield x
and recurse on the tail of the list. I keep filling in …
as an exercise.
Upvotes: 1