你如何在haskell的参数中使用函数? [英] How do you use a function inside arguments in haskell?
问题描述
我遇到了一个问题,要求编写一个将函数应用于整数并计算答案的函数.问题来了:
I am on a problem that asked to write a function that applies a function to an Integer and calculate the answer. Here is the problem:
声明类型并定义一个函数,该函数接受一个函数(比如 f)和一个整数(比如 n)并返回 f 0 + f 1 + f 2 + … + f n.例如,fun sq 5 将返回 55,即 0+1+4+9+16+25(sq"的意思是正方形").
Declare the type and define a function that takes a function (say f) and an integer (say n) and returns f 0 + f 1 + f 2 + … + f n. For example, fun sq 5 would returns 55 which is 0+1+4+9+16+25 ("sq" means "square").
有人知道怎么做吗?我将不胜感激.
Does anyone know how to do that? I would very much appreciate it.
推荐答案
这叫做高阶函数
fun :: (Int -> Int) -> Int -> Int
fun f n = ???
我们只是像普通函数一样使用 f
,写 f 0
或其他什么.???是
And we just use f
like a normal function, writing f 0
or whatever. ??? is the haskell translation of
f 0 + f 1 + ... + f n
至于如何做到这一点,这看起来像家庭作业,所以我只是提示你使用 [0..n]
来获取从 0 到 n<的列表/code> 和
As for how to do this, this looks like homework so I'll just hint you to look at using [0..n]
to get a list from 0 to n
and
map :: (Int -> Int) -> [Int] -> [Int] -- restricting for clarity
将函数应用于列表中的每个项目(嘿,这是另一个高阶函数)
which applies a function to every item in a list (hey it's another higher order function)
sum :: [Int] -> Int
将列表中的所有数字相加.
Which adds up all the numbers in a list.
这篇关于你如何在haskell的参数中使用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!