I'm new to haskell and am working on a function called combineAll
.
Its input is going to be three integer lists, and its output will be one integer list.
It's going to return a sum of the three lists in corresponding order.
For example, if the input value is :
[[1,0,0,0],[1,1,1,0],[1,1,0,0]]
Then the output value will be :
[3,2,1,0]
I defined its signature as:
combineAll :: [[Int]] -> [Int]
I tried zipWith ( )
but since it takes two inputs, it seems impossible for me to build up the recursion.
Any help would be appreciated!
CodePudding user response:
You can turn this problem on its side with transpose
, and transform the resulting list with map
.
The mapping function will be ..... .
To find out what it is, see what will be the type of each element, and what is the value we're interested in producing for them.
CodePudding user response:
This seems like a homework assignment, and you haven't shown code, so I'm not going to present a full solution with code, but generally:
You can map head
across your list of lists. If you do that to [[1,0,0,0],[1,1,1,0],[1,1,0,0]]
you'll get [1, 1, 1]
. You can sum these to get 3
.
If you map tail
across [[1,0,0,0],[1,1,1,0],[1,1,0,0]]
you get [[0,0,0],[1,1,0],[1,0,0]]
. If you apply this recursively, you can get the sums of corresponding elements of the lists in your list of lists.
CodePudding user response:
Another option is to use the transpose
function. With your input that will produce:
ghci> transpose [[1,0,0,0],[1,1,1,0],[1,1,0,0]]
[[1,1,1],[0,1,1],[0,1,0],[0,0,0]]
CodePudding user response:
Check out zipWith3 if you just want to zip 3 lists together.
Alternatively, a more generalised solution would be to fold the list by zipping two int lists together at a time.