As I try to learn Haskell just for fun and the experience I have no other possibility than to ask you the "dumb" questions of a total beginner ^^. I stumbled across the problem how it might be possible to find the sums of lists whithin lists e.g. [[1,3],[4,7],[2,5]] = [4,11,7] and I have found no solution so far. Does anybody have a clue how this might work in Haskell?
问题:
回答1:
Think about function types, it may help.
You have [[Int]]
and you want a function [[Int]] -> [Int]
to get [Int]
The function you want is map sum :: [[Int]] -> [Int]
The following codes was run in ghci
First you have list of list of ints. Note that in this example you need to guide ghci
with [[Int]]
to get the type you want instead of the confusing generic [[1,3],[4,7],[2,5]] :: Num t => [[t]]
Prelude> let xs = [[1,3],[4,7],[2,5]] :: [[Int]]
Next, you might already know sum
, let make one that specific for [Int]
instead of generic sum :: (Foldable t, Num a) => t a -> a
, this will make the type easier to read
Prelude> let sumInts = sum :: [Int] -> Int
Next, let test the sumInts
on some element of xs = [[1,3],[4,7],[2,5]]
Prelude> :t sumInts [1,3]
sumInts [1,3] :: Int
Prelude> sumInts [1,3]
4
Now you can do sum
on an element of a list, to do that to entire list you can use map
Prelude> :t map
map :: (a -> b) -> [a] -> [b]
Let see if you pass sumInts
to a map what type you will get?
Prelude> :t map sumInts
map sumInts :: [[Int]] -> [Int]
This should work with xs :: [[Int]]
but let check type first to make sure
Prelude> :t map sumInts xs
map sumInts xs :: [Int]
Now do the computation
Prelude> map sumInts xs
[4,11,7]
Since sumInts = sum
, this also mean sum
would work too
Prelude> :t map sum xs
map sum xs :: [Int]
Prelude> map sum xs
[4,11,7]
Note 1: map sum
real type is map sum :: (Foldable t, Num b) => [t b] -> [b]
) in the last example it was inferred by type [[Int]]
of xs to [[Int]] -> [Int]
回答2:
You can sum a list with sum
and you can apply any function to each element of a list with map
so the function you are looking for is:
map sum
when you apply the function:
map sum [[1,3],[4,7],[2,5]]
you get your [4,11,7]
. What happens is that map walks over the outer list and keeps applying the function that it gets as its first argument (in this case it is the sum
function) to every element. At the same time, map
collects the results in an output list. So sum
is applied to [1,3]
with the result 4
to [4,7]
with the result 11
and to [2,5]
with the result 7
, all of which are placed in a list [4,11,7]
.