Haskell has a sum function
sum :: Num a => [a] -> a
What can be nicely composed to summarize the matrix on
sum . map sum :: Num a => [[a]] -> a
However, deepening, for example, with the summation of the cube, the restriction Num [a] is created
sum . map sum . map sum :: (Num a, Num [a]) => [[[a]]] -> a
What if you think about it, naturally. Thus, with the previous attempt to define the sumcube function, inflated on one face, we need to find another way. One such attempt:
sum . map sum . map (map sum) :: Num a => [[[a]]] -> a
It seems nowhere more natural than the summation function.
In my quest for using mental tools to solve problems in Haskell, Iām interested in learning how to solve this problem of summing up structures of any depth, say stacking a map sum , as in my third code example. Is it even possible? And in that case, how would you do that?
haskell
Magnus kronqvist
source share