Applying a function to an arbitrarily long list of arguments

I want to create an apply function that takes a function with an arbitrary number 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 it won't work because the type signature is wrong - the function doesn't take a list of ints, it just takes a number of int arguments.

Also, when I get the base case, the f argument to apply must actually be an integer, breaking the type signature anyway.

Does anyone know how to deal with this problem?

+2


a source to share


2 answers


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



Why would you want to do that? Perhaps your argument structure should be passed as a data structure, but so far you have held back the problem to ensure it doesn't create an idiomatic Haskell solution.

+11


a source


You can do it with some cool class types



{-# 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]

      

+7


a source







All Articles