i need to write a function, which takes positive integers list. If list begins with 2, then every element must be multiplied by 2, in other cases every integer n is written n-1 times.
two :: [Int] -> [Int]
i.e:
two [2,1] ==> [4,2]
two [3,2,4] ==> [3,3,2,4,4,4]
multiplyEveryoneByTwo :: [Int] -> [Int]
multiplyEveryoneByTwo [] = []
multiplyEveryoneByTwo [x] = [x*2]
multiplyEveryoneByTwo (x:xs) = (x*2) : multiplyEveryoneByTwo xs
replicateEveryone :: [Int] -> [Int]
replicateEveryone [] = []
replicateEveryone [x] = replicate (x-1) x
replicateEveryone (x:xs) = (replicate (x-1) x) ++ replicateEveryone xs
two :: [Int] -> [Int]
two [x] = if x == 2 then [x*2] else replicate (x-1) x
two (x:xs)
| x == 2 = multiplyEveryoneByTwo (x:xs)
| otherwise = replicateEveryone (x:xs)
I’m stuck now with writing that: if my first element of the list is 2, then recursively multiply every element by 2. I tried to do with extra function multiplyByTwo but it doesn’t work.
The else statement is that i need to replicate every element of the list by (itself – 1)
is it correct approach to pass (x:xs) to my helper functions in here | x == 2 = multiplyEveryoneByTwo (x:xs) | otherwise = replicateEveryone (x:xs)
I would suggest separating your problems into two separate functions
After you have these two functions tested and working you can create your weird function that combines them