Reader Level:
Articles

FSharp for Beginners: What is the List.Map Function?

By Dhananjay Kumar on Oct 01, 2011
Here you will learn how the List.map function creates a new collection by applying a function to the given collection.
  • 0
  • 0
  • 5035

The List.map function creates a new collection by applying a function to the given collection.

list map in fsharp 

Just have a look at the below example,

fsharp in listmap

When you print r1 you should get output like 2,3,4,5

let data = [1;2;3;4]
let functiontomap  r = r+ 1 
let r1 =  List.map functiontomap data  
printfn 
"updated data  = %A" r1
open System 
printfn 
"Press any key to continue"
Console.ReadKey(
true);

Expected output

listmap function

In previous example, I explicitly defined the input function, however, it is not required, you can use List.map as below:

List-map

In the above way of using List.map, we are directly applying a function to the input collection.

let data = [1..10]
let resultincrement = data |> List.map (fun x -> x + 1)
let resultsquare = data |> List.map (fun x -> x*x)
printfn 
"incremented data  = %A" resultincrement
printfn 
"squared data = %A" resultsquare
open System 
printfn 
"Press any key to continue"
Console.ReadKey(
true
);

Expected output

fsharp Listmap

If you want to covert the above integer collection to strings, that also is very much possible in a single line statement, like below:

fsharp Listmap

As the input function you need to pass a string

let data = [1..10]
let stringdata = data |> List.map string 
printfn 
"String data = %A" stringdata
open System 
printfn 
"Press any key to continue"
Console.ReadKey(
true
);

Expected output

listmap function

I hope this post was useful. Thanks for reading

If you find my posts useful you may like to follow me on twitter http://twitter.com/debug_mode or may like Facebook page of my blog http://www.facebook.com/DebugMode.Net If you want to see post on a particular topic please do write on FB page or tweet me about that, I would love to help you.

Dhananjay Kumar

Dhananjay kumar is an independent trainer, a consultant and a programmer from India. He has mentored more than 1000 professionals and known for his unique way of teaching. He has been part of the multiple projects for bi... Read more

Personal Blog: http://debugmode.net/
COMMENT USING

Trending up