MohamedMansour
MohamedMansour

Reputation: 63

writing a recursive function using foldr

I am new in Haskell programming. While practicing I was asked to make a recursive function that looks like this:

repeat1 5 [1,2,3] = [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]

which is

repeat1 :: Int -> a -> [a]
repeat1 0 x = []
repeat1 num x = x : repeat1 (num-1) x

I want to convert it into a foldr function but I can't :(
I have read about the lambda functions and the folding(foldr and foldl) functions from http://en.wikibooks.org/wiki/Haskell/List_processing

Can anybody help please?
Thanks in advance

Upvotes: 1

Views: 638

Answers (3)

Jerome
Jerome

Reputation: 4572

If you really want to use foldr, you could do something like that:

repeat' n x = foldr (\_ acc -> x:acc) [] [1..n]

You basically create a list of size n with [1..n] and for each element of that list, you append x to your accumulator (base value []). In the end you have a n-elements list of x.

Upvotes: 1

Landei
Landei

Reputation: 54584

As hammar pointed out, foldr isn't the right tool here, as you first need a list to work on. Why not simply...

repeat1 n = take n . repeat 

Upvotes: 2

hammar
hammar

Reputation: 139870

foldr is for functions that consume lists. For producing lists, unfoldr is a more natural choice:

repeat1 :: Int -> a -> [a]
repeat1 n x = unfoldr f n
  where f 0 = Nothing
        f n = Just (x, n-1)

That said, I think writing it as a plain recursion is more clear in this case.

Upvotes: 4

Related Questions