Applying a function to an arbitrarily long list of arguments

半城伤御伤魂 提交于 2019-12-24 05:17:09

问题


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?


回答1:


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.




回答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]


来源:https://stackoverflow.com/questions/2800204/applying-a-function-to-an-arbitrarily-long-list-of-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!