Haskell - 如何将地图总和(地图(x :) xss)转换为地图(x +)(地图总和xss) [英] Haskell - How to transform map sum (map (x:) xss) to map (x+) (map sum xss)
问题描述
map sum(map(x :) xss)
重写为 map(x +)(map sum xss)
直觉上我知道它是有道理的...
如果你有一些列表,你可以总结一下,但是在求和之前,你也要添加一个元素'x',那么就和
但是我想知道如何使用等式推理将其转换成另一个。我觉得我错过了一个可以帮助我理解的法律或规则。
使用法律 map f(map g list)=== map(f。g)list
我们可以推导出
map sum(map(x :) xss)=
map(sum。(x :))xss =
eta-expand ($ \\ xs - > sum。(x :) $ xs)xss = $ p
$ b
代入(f。g)x === f(gx )
map(\xs - > sum(x:xs))xs =
其中
sum(x:xs)= x + sum xs
sum [] = 0
< (x:xs))xss =
地图(\ xs - > sum(x:xs))
$ b
map \ xs - > x + sum xs)xss =
替换 f (gx)===(f。g)x
map( \\ xs - >(x +)。sum $ xs)xss =
eta-reduce the lambda
map((x +))。总和)xss =
使用上面的第一个定律的逆向
map(x +)(map sum xss)
Reading "Thinking Functionally with Haskell" I came across a part of a program calculation that required that map sum (map (x:) xss)
be rewritten as map (x+) (map sum xss)
Intuitively I know that it makes sense ...
if you have some lists that you are going to sum but, before summing, to those same lists you are also going to add one element 'x', then that is the same as taking a list of sums of the origninal lists and adding x's value to each of them.
But I would like to know how to transform one into the other only using equational reasoning. I feel like I'm missing a law or rule that would help me understand.
Using the law
map f (map g list) === map (f . g) list
We can deduce
map sum (map (x:) xss) =
map (sum . (x:)) xss =
eta-expand to give an argument to work with
map (\xs -> sum . (x:) $ xs) xss =
Substituting in for (f . g) x === f (g x)
map (\xs -> sum (x:xs)) xs =
Where
sum (x:xs) = x + sum xs
sum [] = 0
so
map (\xs -> sum (x:xs)) xss =
map (\xs -> x + sum xs) xss =
Substituting f (g x) === (f . g) x
map (\xs -> (x +) . sum $ xs) xss =
eta-reduce the lambda
map ((x +) . sum) xss =
The use the reverse of the first law from above
map (x+) (map sum xss)
这篇关于Haskell - 如何将地图总和(地图(x :) xss)转换为地图(x +)(地图总和xss)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!