user1226239
user1226239

Reputation: 69

Functional Programming, Haskell applying a function to a list of variables

I have a function of type Csp -> Var -> Int -> Csp, and I want to apply this function to a list of [Var], just wondering if anyone can help me out I'm totally bamboozled!

Upvotes: 1

Views: 528

Answers (6)

Tilo Wiklund
Tilo Wiklund

Reputation: 821

What you want is a fold. foldl has the signature foldl :: (a -> b -> a) -> a -> [b] -> a, so in your case you want a to be Csp h and b to be Var, giving you the type foldl :: (Csp -> Var -> Csp) -> Csp -> [Var] -> Csp. For the first argument you just pass it something like \csp var -> f csp var yourFixedInt where f is your function.

If you aren't familiar with folds what this does is apply, for each var in your list of Vars, the function you pass it (in this case just your function with the Int argument fixed) to a Csp accumulator and var.

(There are a lot better explanations of folds around, but I figured I'd include at least a short comment)

Upvotes: 2

Boris
Boris

Reputation: 5176

I think you need a fold.

answer :: (Csp -> Var -> Int -> Csp) -> Csp -> [Var] -> Int -> Csp
answer f csp vs i = foldl (\csp' v -> f csp' v i) csp vs

Upvotes: 1

amindfv
amindfv

Reputation: 8448

map takes a function and applies it to a list of values. So as a simple example, if I have a function f x = x + 5, and a list l = [1,2,3], then map f l will return [6,7,8]

Given f :: Csp -> Var -> Int -> Csp, and l :: [Var], you should write

map (\x -> f csp x int) l -- note that the variable names (like "csp") can be anything

which will have the type :: Csp -> Int -> Csp. In other words, it will return a list of functions.

Upvotes: 0

hammar
hammar

Reputation: 139830

From your comment, it sounds like you want a fold, for example:

foo :: Csp -> Var -> Int -> Csp -- your function

bar :: Csp -> [Var] -> Int -> Csp
bar c0 vs x = foldl (\c v -> foo c v x) c0 vs

Though it might be worth changing the order of the arguments a little to make it more suited for partial application:

foo :: Int -> Csp -> Var -> Csp

bar :: Int -> Csp -> [Var] -> Csp
bar x = foldl (foo x)

Upvotes: 7

Ingo
Ingo

Reputation: 36329

You want a fold, or so it sounds to me. Suppose the function you have is f

f :: Csp -> Var -> Int -> Csp
vars = [ ..... ] :: [Var]
i :: Int -- the constant int argument to f

foldl g vars where g c v = f c v i

Upvotes: 1

pcalcao
pcalcao

Reputation: 15965

http://zvon.org/other/haskell/Outputprelude/map_f.html

This might be what you're looking for, no?

Upvotes: 1

Related Questions