Alex_P
Alex_P

Reputation: 2950

How to use a lambda operation input in a function parameter?

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

Answers (1)

Brian Berns
Brian Berns

Reputation: 17153

Higher-order functions

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

List.map

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.

Implementing your own map function

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:

  • Given a function f and a list of items:
    • If items is empty, return the empty list
    • Else items is not empty:
      • Let value be the result of applying f to the first element of items
      • Let rest be the result of recursively mapping f to the remainder of the items
      • Return a new list that consists of value followed by rest.

Hint: Use pattern matching to convert this into F# code.

Solution


 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

Related Questions