F# Loop through a list of functions, applying each function in turn to a number

Viewed 1052

I've recently started learning F#. I'm attempting to loop through a list of functions, applying each function to a value. For example, I have:

let identity x = fun x -> x
let square x = fun x -> x * x
let cube x = fun x -> x * x * x

let functions = [identity; square; cube]

I would now like to do something like the following:

let resultList = List.map(fun elem -> elem 3) functions

where the result value would be the list [3;9;27]. However, this is not what happens. Instead, I get:

val resultList : (int -> int) list = [<fun:Invoke@3000>; <fun:Invoke@3000>; <fun:Invoke@3000>]

I guess I'm not entirely convinced that using map is the right way forward any longer, so my questions are:

  1. Why do I not get a list of numbers?
  2. How would return a list of numbers?
  3. What does <fun:Invoke> mean?

Thanks very much for your help.

Daniel

2 Answers

Because I like to simplify where I can, you can reduce a bit on Joachim's answer by removing the fun from your functions:

let identity x = x
let square x = x * x
let cube x = x * x * x        
let functions = [identity; square; cube]

printfn "%A" (List.map(fun elem -> elem 3) functions)

Gives the output [3; 9; 27]

For me this is more natural. I didn't understand why the functions themselves needed to wrap funcs, rather than simply be the function.

Related