将函数应用于任意长的参数列表
我想创建一个函数 apply,它接受带有任意数量参数的函数以及整数列表,并返回函数的结果(其中列表中的每个整数都是按顺序排列的参数。
我在想类似的事情:
apply :: ([Int] -> Int) -> [Int] -> Int
apply f x:xs = apply (f x) xs
apply f [] = f
但我知道这行不通,因为类型签名是错误的 - 该函数不接受整数列表,它只接受一些 int 参数
此外,当我到达基本情况时,要应用 f 参数。实际上应该是一个整数,无论如何都违反了类型签名。
有谁知道如何处理此类问题?
I want to create a function apply that takes a function with an arbitrary amount of arguments as well as a list of integers, and returns the result of the function (Where each integer in the list is an argument in order.
I was thinking something like:
apply :: ([Int] -> Int) -> [Int] -> Int
apply f x:xs = apply (f x) xs
apply f [] = f
But I know this won't work because the type signature is wrong - the function doesn't take a list of ints, it just takes some amount of int arguments.
Additionally, when I get to the base case the f argument to apply should actually be an integer, violating the type signature anyway.
Does anyone know how to deal with this sort of problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为什么要这样做?也许你的参数结构应该作为数据结构传递,但到目前为止你已经过度限制了问题以确保它不会产生惯用的 Haskell 解决方案。
Why do you want to do this? Perhaps your argument structure should be passed as a data structure, but so far you've over constrained the problem to ensure it won't produce an idiomatic Haskell solution.
你可以用一些奇特的类型类来做到这一点
You can do it with some fancy type classes