Question
Haskell list sum generalization
I was working in Python and created an example of how we can generalize the usual sumList
function to sum any arbitrary list of lists:
- To sum any list of numbers in Python we can write:
def sumList(xs):
if xs==[]:
return 0
else:
return xs[0]+sumList(xs[1:])
And in Haskell:
sumList [] = 0
sumList (x:xs) = x + sumList xs
- but to sum an arbitrary nested list, in Python we have:
def sumList2(xs):
if xs==[]:
return 0
elif isinstance(xs,int):
return xs
else:
return sumList2(xs[0])+sumList2(xs[1:])
But the following Haskell code throws a compiler error in the type inference:
sumList [] = 0
sumList (x:xs) = sumList x + sumList xs
sumList x = x
<interactive>:2:38: error:
• Couldn't match expected type ‘t’ with actual type ‘[t]’
‘t’ is a rigid type variable bound by
the inferred type of sumList :: t -> [t]
at <interactive>:(1,1)-(3,13)
• In the first argument of ‘sumList’, namely ‘xs’
In the second argument of ‘(+)’, namely ‘sumList xs’
In the expression: sumList x + sumList xs
• Relevant bindings include
xs :: [t] (bound at <interactive>:2:12)
x :: t (bound at <interactive>:2:10)
sumList :: t -> [t] (bound at <interactive>:1:1)
I am using IHaskell, for what I understand, when using sumlist [] = 0
as pattern matching, Haskell inferrs that sumList :: [a] -> number
, but then when I pass sumList
x
in the next line, x
is the head of the list, so sumList :: a -> number
, so it gets an absurd. What I figured is that I need to match the case where the input is a list and do the 2 first lines, and then the case where the input is an integer and do the last line, but I cannot figure out how to do it.
I am trying to create a sum type of Either Int [a]
, but I don't know if that is the better answer, because I want to let the compiler figure out everything related to types (ultimately I will write the type definition, but my initial thesis is that contrary to popular belief, it is possible to do quick experimentation in Haskell, and so that means to not be concerned with types in the first stage of programing). Note the shortcomings of the for loop, it would be very difficult or impossible to generalize the sum of the list using for loops, because of the linearity of the loop, I think it is a very compelling argument for the scaling of machine learning software.