DragonS
DragonS

Reputation: 41

How do i implement the take function in Haskell using takeWhile?

So in my exam i had to implement the take function in Haskell using the takeWhile.

How can i do this?

What would be the condition in takeWhile so that it will only take the required number of elements from the list?

Because to my understanding in takeWhile the condition refers to the elements of the list, not the number of those.

Upvotes: 1

Views: 5817

Answers (2)

DragonS
DragonS

Reputation: 41

DONE!!!

Thanks a lot for the help everyone!

I know this could work better but for now this solution worked out.

index function:

index :: [a] -> [(Int, a)]
index [] = []
index x = index2 x 1

index2 :: [a] -> Int -> [(Int, a)]
index2 [] _ = []
index2 (x:xs) i = (i, x) : index2 xs (i+1)

deindex function:

deindex :: [(Int, a)] -> [a]
deindex [] = []
deindex ((i,x):xs) = x : deindex xs

myTake function using takeWhile:

myTake :: Int -> [a] -> [a]
myTake k _
    | k <= 0 = []
myTake _ [] = []
myTake n list = deindex (takeWhile (\ (x,y) -> x<=n) (index list))

Upvotes: 0

Will Ness
Will Ness

Reputation: 71119

to my understanding in takeWhile the condition refers to the elements of the list, not the number of those

Yes! Except, maybe, perhaps, we could somehow make each element reflect the number of its preceding elements in the list, i.e. its index in the list.

So we would need to transform our argument list

[ a, b, c, .... ]

into a new, modified one, containing the extended information in its elements, e.g.

[(a, what?), (b, goes?), (c, here?), .... ]

and then craft some kind of predicate on these pairs to do what we want; then recover the original elements from the pairs, following the decorate--transform--undecorate paradigm.

If you aren't familiar with the built-in higher-order functions that can accomplish these tasks, you can code them up with recursion, yourself. Or use list comprehensions.

Upvotes: 3

Related Questions