0

Basic question... I wish to map over a list and apply a function to each element, however I want to execute this from another function:

functionOne :: Int -> Int -> Int --Add x to each element of the list
functionOne element x = element + x 

functionTwo :: [Int] -> (Int -> Int -> Int) -> [Int]
functionTwo list fOne = map list fOne ave --map list by applying functionOne with ave as x
   where 
     ave = ((sum list) / length list)

Why isn't this working?

1 Answer 1

2

You probably want this:

functionTwo :: [Int] -> (Int -> Int -> Int) -> [Int]
functionTwo list fOne = map (\el -> fOne el ave) list
   where 
     ave = sum list `div` length list

Above, we use the anonymous function (\el -> fOne el ave), which is the function mapping each el to fOne el ave. In this way, we fix the second argument of fOne to the wanted value.

Alternatively,

functionTwo :: [Int] -> (Int -> Int -> Int) -> [Int]
functionTwo list fOne = map (flip fOne ave) list
   where 
     ave = sum list `div` length list

Note div for integer division, / only works on floating point numbers.

flip f is the same function as f, but with the first two arguments in the other order.

Also possible: map (`fOne` ave) list.

Sign up to request clarification or add additional context in comments.

4 Comments

Can you explain, from your first example, what '(\el -> fOne el ave)' is doing? then i can accept
@barbrac That's the syntax for a function. It's \PARAMETER -> BODY, i.e. in this case it's a function taking a value (el) and returning fOne el ave.
Why flip? Addition is commutative, so just map (fOne ave) list.
@amalloy Addition is, but I think the OP wanted the general case, since she specified "with ave as x".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.