F# Tip of the Week (26 August 2013)

It’s possible to use function composition and modify the type of value returned.  Consider the following equation:

1/4x2

I might encode the function to calculate this like so:


let square x = x * x

//Want this to be a float because if this is an int division

// it will always round to 0 if x is greater than 1.

let recip x = 1.0/x

let myFunc =  fun x -> 4* (square x) >> recip

This function composition will not work because I need to pass a float to recip. But I can make it work by doing this:


let square x = x * x

let recip x = 1.0/x

let myFunc = fun x -> 4* (square x) >> float >> recip

 

There’s a great deal more information on conversion functions in F# here.

One response

  1. Pingback: F# Weekly #35 2013 | Sergey Tihon's Blog

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

%d bloggers like this: