I am doing a programming exercise in Haskell, in which I give some values in a list, for example [1, 2, 2, 3, 4] and it should be as follows [1, 4, 3, 4]. So far the program works without problems for me with the following code:
sustituirSumando [x,y]
| x==y = [x+y]
| otherwise = [x,y]
sustituirSumando [x,y,z]
| x==y = [x+y,z]
| y==z = [x,y+z]
|otherwise = [x,y,z]
sustituirSumando (x:y:xs)
| x==y = (x+y) : sustituirSumando (xs)
| otherwise = x: sustituirSumando (y:xs)
Where I don't know how to proceed is in the following supposed example [1, 2, 2, 4, 5] here the list should be as follows [1, 8, 5] but in my code it remains [1, 4, 4, 5]. Thanks in advance.
You can create a function that receives two lists of
int
as inputs and returns a list ofint
. We need two inputs so that we can use recursion in the function.The first entry is a list that stores the result of each iteration. In the first iteration, the first list must be empty (
[]
).The second entry is the rest of the list that has not been processed in the function.
We do the operation step by step.
At each iteration, we test whether the last element of the first list is equal to the first element of the second list. The iteration ends when no element exists in the second list.
Here we use the
init
and functionslast
to get specific parts of a list.Code:
Example:
If execute
suma1 [] [1, 2, 2, 4, 5]
, the operation is:If you don't want to pass an empty list as an argument, you can call
suma1
from another function:In the recursion, you have to add the addend to the list again. Something like that: