FSharp for beginners: what is List.map function?

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

clip_image001

Just have a look on below example,

clip_image002

When you print r1 you should get the output as 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

clip_image002

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

image

In above way of using List.map, we are directly applying 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

clip_image002[6]

 

If you want to covert above integer collection as string , that also very much possible in single line of statement as below,

clip_image004

As input function you need to pass 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

clip_image002[8]

I hope this post was useful. Thanks for reading  Smile

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.

2 thoughts on “FSharp for beginners: what is List.map function?

  1. Pingback: Monthly Report September 2011: Total Posts 28 « debug mode……

  2. Pingback: Link Resource # 27 : Oct 03 – Oct 06 « Dactylonomy of Web Resource

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s