Reputation: 2950
To be honest, I am not even sure how to correctly phrase the question.
I want to write a function which can accept a lambda operation i.e. (x -> x + x) as a parameter which is then applied to each entry of a list. This task is from the F# - Accumulate task by exercism.io.
As I did not find any example of this kind of function input, I have no idea how I can use this lambda input.
Upvotes: 1
Views: 120
Reputation: 17153
A function that accepts a lambda as a parameter is called a "higher-order function". These are very common in functional programming. Here's a simple example called apply
, which is a higher-order function that takes another function (or lambda) called f
and applies it to a value x
.
// ('a -> 'b) -> 'a -> 'b
let apply f x = f x
Any higher-order function that applies a given function to every element of a collection is called a "map". For lists, the specific function you want is called List.map
, and is already provided by the F# standard library.
If you're not allowed to use the built-in List.map
for this exercise, you can implement the same thing yourself easily via recursion. I don't want to give away the solution prematurely, so I'll describe it in pseudo-code first:
f
and a list of items
:
items
is empty, return the empty listitems
is not empty:
value
be the result of applying f
to the first element of items
rest
be the result of recursively mapping f
to the remainder of the items
value
followed by rest
.Hint: Use pattern matching to convert this into F# code.
let rec mymap f items = match items with | [] -> [] | head :: tail -> let value = f head let rest = mymap f tail value :: rest
Note: This is a verbose implementation. If desired, you can make it considerably smaller.
Upvotes: 3