[英]Haskell - Calculate sum of functions by creating a higher class function
Without the usage of imported code (i can use head, tail
, init
, last
, filter
, map
, fold
, .
, generally basic haskell functions ) I want to create a higher-order function int ,type hof :: [Integer->Integer]->(Integer->Integer)
, with hof s = \\n ->....
(using lambda) that implements the following math formula没有进口代码使用(ⅰ可以使用头,
tail
, init
, last
, filter
, map
, fold
, .
,通常基本Haskell函数)我想创建一个高阶函数int,型hof :: [Integer->Integer]->(Integer->Integer)
,使用hof :: [Integer->Integer]->(Integer->Integer)
hof s = \\n ->....
(使用 lambda)实现以下数学公式
(sorry, it is hand-written)
(对不起,是手写的)
Need some basic guidence for starting , i thought about implementing a recoursive call each time of the hof function , which hof itself should implement a changed math formula(which i given) suitable for recursive tail calls.需要一些基本的开始指导,我想过每次执行 hof 函数时都实现一个递归调用,hof 本身应该实现一个适合递归尾调用的已更改数学公式(我给出的)。
some results that should be produced :应该产生的一些结果:
Main> map (hof [(+1)]) [1..10]
[2,3,4,5,6,7,8,9,10,11]
Main> map (hof [(+1),(+2)]) [1..10]
[3,4,6,7,9,10,12,13,15,16]
Main> map (hof [(2^),(2^),(2^),(2^),(2^)]) [5..12]
[42,85,170,341,682,1364,2728,5456]
Main> map (hof [(*2),(+100),(^3),negate,(mod 100)]) [24..40]
[2768,3151,3567,4020,4509,5038,5609,6221,6876,7575,8322,9117,9960,10855,11805,
12806,13863]
Main> map (hof [(mod 100),negate,(+100),(^3),(*2)]) [24..40]
[1181,1351,1562,1767,1989,2230,2490,2771,3071,3395,3774,4145,4539,4958,5402,5873,6369]
Main> map (hof [(‘mod‘ i) | i<-[50..100] ]) [1000..1030]
[23,24,27,28,30,32,35,36,39,40,37,38,40,41,44,45,47,48,52,53,55,31,33,35,37,39,42,
45,46,48,47]
Thanks for reading !谢谢阅读 !
Let's say you have a list of functions:假设您有一个函数列表:
fs = [f1, f2, f3, f4, f5] -- or more
Now, for each value i
from 0 to infinity, we want to apply a function from fs
to a corresponding n - i
, then divide that value by 2 i , and we want to sum the resulting floors.现在,对于从 0 到无穷大的每个值
i
,我们希望将fs
的函数应用于相应的n - i
,然后将该值除以 2 i ,然后我们想要对结果楼层求和。
hof fs = \n -> sum [ fi (n-i) `div` (2^i) | (fi, i) <- zip fs [0..]]
Even though [0..]
is an infinite list, the result of zip fs [0..]
is finite, limited by the length of fs
.尽管
[0..]
是一个无限列表, zip fs [0..]
是有限的,受fs
的长度限制。
To avoid repeated multiplications for each successive power of 2, use the iterate
function to compute a sequence of them to zip along with fs
and [0..]
为了避免对 2 的每个连续幂进行重复乘法,请使用
iterate
函数计算它们的序列以与fs
和[0..]
一起压缩
hof fs = \n -> sum [fi (n-i) `div` k | (fi, i, k) <- zip3 fs [0..] (iterate (*2) 1)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.