Define a function replicate which given a list of numbers returns a
list with each number duplicated its value. Use a fold, map, and take
..> replicate [5,1,3,2,8,1,2]
output: [5,5,5,5,5,1,3,3,3,2,2,8,8,8,8,8,8,8,8,1,2,2]
I’ve figure this out using List comprehension and recursion:
replicate2 [] = []
replicate2 (n:nn) = take n(repeat n) ++ replicate2 nn
but how would you use fold and map to do this?
so far I have: replicate n = map (foldl1 (take n(repeat n)) n) n
which is obviously wrong, but I think I am close..
so any help would be nice, THANKS!
The key in Haskell is always follow the types:
I’ve added some spaces here to make it a bit more clear how these three functions compare. Remember when you look at these that a type variable,
aorb, can match any type, including things likeString, or[Float], or even[(String,[Int])]. For example, in the expression:foldris being used as type([Int] -> Int -> Int) -> Int -> [[Int]] -> Int. That isahas matched[Int]andbhas matchedInt.Now: Think about at the “outermost” level what your expression has to do. Which of these functions fits that form?
Can you cast your problem into an outer expression that has one of these forms and an “inner” problem?