将函数应用于任意长的参数列表

发布于 2024-08-31 12:31:59 字数 345 浏览 9 评论 0原文

我想创建一个函数 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

神回复 2024-09-07 12:31:59

我想创建一个函数 apply,它接受一个带有任意数量参数的函数以及一个整数列表,

为什么要这样做?也许你的参数结构应该作为数据结构传递,但到目前为止你已经过度限制了问题以确保它不会产生惯用的 Haskell 解决方案。

I want to create a function apply that takes a function with an arbitrary amount of arguments as well as a list of integers,

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.

耳根太软 2024-09-07 12:31:59

你可以用一些奇特的类型类来做到这一点

{-# LANGUAGE FlexibleInstances #-}
-- for ApplyType (Int -> r)

class ApplyType t where
    apply :: t -> [Int] -> Int

instance ApplyType Int where
    apply f _ = f

instance (ApplyType r) => ApplyType (Int -> r) where
    apply f (x:xs) = apply (f x) xs

main :: IO ()
main = do print $ apply ((+) :: Int->Int->Int) [1, 2]
          print $ apply ((\x y z w -> x*y - z`div`w) :: Int->Int->Int->Int->Int) [3,5,8,2]

You can do it with some fancy type classes

{-# LANGUAGE FlexibleInstances #-}
-- for ApplyType (Int -> r)

class ApplyType t where
    apply :: t -> [Int] -> Int

instance ApplyType Int where
    apply f _ = f

instance (ApplyType r) => ApplyType (Int -> r) where
    apply f (x:xs) = apply (f x) xs

main :: IO ()
main = do print $ apply ((+) :: Int->Int->Int) [1, 2]
          print $ apply ((\x y z w -> x*y - z`div`w) :: Int->Int->Int->Int->Int) [3,5,8,2]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文