Typing the command into F# interactive (from the left column) we can see the value of our expression and investigate some of the different types we'll be running into.
Note: In case you don't have the F# environment, in my previous post I talked about how to get everything set up.
Command |
Response |
Type |
3;; |
val it : int = 3 |
int - Int32 |
3u;; |
val it : uint32 = 3u |
Unsigned int - Uint32 |
3L;; |
val it : int64 = 3L |
Long - Int64 |
3UL;; |
val it : uint64 = 3UL |
Unsigned Long - UInt64 |
3s;; |
val it : int16 = 3s |
short - Int16 |
3us;; |
val it : uint16 = 3us |
Unsigned short - UInt16 |
3.0;; |
val it : float = 3.0 |
Float - floating point |
"Hello World";; |
val it : string = "Hello World" |
String |
'c';; |
val it : char = 'c' |
Character |
These are pretty simple… Let's look at something that will seem a bit new to C# imperative programmers:
Command |
Response |
(+);; |
val it : (int -> int -> int) = <fun:it@42> |
As you can see, the "(+)" actually has a value in F#. The value of "(+)" in F# takes our int operator and turns it into a prefix function that accepts two integers (the first two ints in "int -> int -> int") and has a return value of an integer ("int -> int -> int"). Another way to look at it is:
In F# (and all functional programming languages) the function is a first class value, just like numbers and characters. This takes a bit of getting used to but is really the power and beauty behind the language.
If we want, we can define our own functions using the function syntax (above). The keyword for creating our own function is "fun". Let's define a function that returns the same value we passed in.
Command |
Response |
fun x -> x;; |
val it : 'a -> 'a = <fun:clo@0_1> |
Now we have declared a new function that takes and 'a ('a->'a) and returns an 'a ('a->'a) . What's it mean?
F# tries to be as generic as possible by default. 'a is a generic "type" so anytime you see something like 'a, think to yourself "something that is an a" or "something of type a". If you are familiar with C# this would have the same idea as the following generic function except in the generic function we use 'T' instead of 'a:
public T DoSomething<T>(T value)
{
return value;
}
So what happens if we constrain the output a bit? We know "(+)" is an "int -> int -> int" so what if we supply one of the parameters? What would "(x + 1)" be?
Command |
Response |
fun x -> x + 1;; |
val it : int -> int = <fun:clo@0_2> |
You can see, we now have a function that will take an int as the input parameter ("int -> int") and will receive and int as the result of the operation ("int -> int").
The thing to notice is that the interpreter will interpret the variable types and do this as generically as possible which makes for much greater code reuse. This also forces to think generically and will help make us better C# programmers.
Here is another example using a string.
Command |
Response |
fun x -> x + " World";; |
val it : string -> string = <fun:clo@0_3> |
We don't have to specify the type but it is in there.
In the interpreter, we can apply functions and immediately see the results. For example, if we type "3+3;;" we get the following:
> 3+3;;
val it : int = 6
Really, the "+" by itself is just an operator (and not really a function). We have to surround the "+" with parenthesis "(+)" to turn it into a function.
To demonstrate, if we enter "+;;" as a command by itself we receive an error:
> +;;
+;;
--^^^
stdin(63,2): error: syntax error.
But if we wrap it in parenthesis like "(+)", we now have a function.
> (+);;
val it : (int -> int -> int) = <fun:it@65>
This function expects two integers and returns an integer so we pass the first two parameters into the function in the following way:
> (+) 3 3;;
val it : int = 6
\
We can do the same thing with strings because the operator is overloaded for string concatenation and the interpreter can figure out the necessary overload operator to use:
> (+) "Hello " "World";;
val it : string = "Hello World"
We can declare our own function and have it behave the same way:
> (fun x y -> x + y) 3 4;;
val it : int = 7
The first value "3" is applied to the first parameter of our method (x) , and the second value gets applied to the second parameter of our method (y), then the function is executed and we see the result as 7.
\
The same thing works with string concatenation:
> (fun x y -> x + y) "Hello " "World";;
val it : string = "Hello World"
Partial application.
What if we provide only one of the two parameters required by our function?
> (fun x y -> x + y) 3;;
val it : (int -> int) = <fun:it@79>
We now have defined a new function of type "int -> int" which is kind of like the function (fun y -> y + 3). This function is only partially applied. So we can now use this partially applied function and apply the last input.
((fun x y -> x + y) 3) 4;;
val it : int = 7
So what's happening? First, our function is interpreted as "int -> int -> int"
\
Next, the value "3" is applied to the first member of our function "int -> int -> int" and we are left with the last two "int -> int -> int"
\
Our new function "int -> int" will add 3 to any value that is applied to it so when we apply "4" to the next position the function can be evaluated to an integer.
\
This may seem pretty basic, but here's point. With functional programming we often have to think of functions not in terms of something that is applied to two values, but as a transformation of our inputs which are applied to our function. You'll see more once we get into lists in an upcoming article.
Here's an example of what I'm talking about... What if we want a way to apply a value from the left hand side of our equation instead of the having the input on the right? To do this we have a special F# forward-pipe operator "|>" which we can think of as the push operator because it "pushes" the value from the left hand side of the function to the first parameter of the function.
So now we have a bunch of different ways to express the same thing
> 4 |> (fun x y -> x + y) 3;;
val it : int = 7
The precedence is pretty important here. Just like in most programming languages, everything in parenthesis are evaluated first (our function). In this code, the right hand side of the "|>" operator is evaluated before the left. (If there are a series of "|>" operators they are applied left to right after their contents have been evaluated, "pushing" the data from left to right.)
So after our function is intrepreted, we apply 3 to the first input
\
And are left with (int->int). Then we apply 4 to the beginning of (int->int) to get the result (7).
Take a look at the following declaration and see if you can figure out what's happening in the following three commands (remember, anything in parenthesis is executed first):
> 4 |> ( 3 |> fun x y -> x + y);;
val it : int = 7
> "World" |> (fun x y -> x + y) "Hello ";;
val it : string = "Hello World"
> ("World" |> (fun x y -> x + y)) "Hello ";;
val it : string = "WorldHello "
See if you can follow what's happening in the following statement:
> "World" |> ("Hello " |> (fun x y z -> x + y + z)) "There ";;
val it : string = "Hello There World"
Anyways… the forward-pipe operator ("|>") will be one of your best friends in F# so it is important to understand how it works.
Let's look at the definition of our push operator in a bit more detail by looking at the definition just like we did with the addition operator earlier "(+)":
> (|>);;
val it : ('a -> ('a -> 'b) -> 'b) = <fun:it@100>
This is confusing at first, but will make sense the more you see it. Let's break it down...
We have a function that takes something of type a in as a first parameter:
('a -> ('a -> 'b) -> 'b)
As a second parameter, our function takes in another function! This second parameter function takes something of type a (again) and outputs something of type b:
('a -> ('a -> 'b) -> 'b)
The final output is our thing of type b:
('a -> ('a -> 'b) -> 'b)
Let's take a look at how the compiler can figure the types out...
If we have our function:
> fun x y -> x + y;;
val it : int -> int -> int = <fun:clo@0_5>
And push "4" in
4 |> fun x y -> x + y;;
val it : (int -> int) = <fun:it@103>
We are saying 4 is our first member so we know 'a is an int
4 |> fun x y -> x + y;;
('a -> ('a -> 'b) -> 'b)
So we end up with a signature where 'a has been constrained to an int
(int -> (int -> 'b) -> 'b)
This is one of the nice things about using the forward pipe. Because F# is generic, it sometimes needs help figuring out what types should be applied to the generic functions and using the pipe operator makes this explicit earlier in the statement. This means we don't have to be as explicit with our types which will make coding much easier.
We know that our function is using integers and now has to be (int -> int -> int)
> fun x y -> x + y;;
val it : int -> int -> int = <fun:clo@0_6>
so our addition function is applied to the second parameter of our forward pipe
4 |> fun x y -> x + y;;
(int -> (int -> 'b) -> 'b)
So what's 'b?
We know our addition function after applying the integer "4" is of type
(int -> int -> int)
Which is getting applied to our second function parameter
(int -> 'b)
(int -> int->int)
So 'b has to be a function that takes an int and returns an int "(int -> int)" which is true because after our partial application we have function that adds 4 to anything we pass in.
This default generic way of thinking and applying functions to other functions is one of the challenging things to understand when making the move from imperative C# to functional F# programming so take your time and try to make as much sense of this as you can. Thinking generically in this way will often help you see a bigger picture whether you are working with imperative or functional code.
Let's look at a sample from a C# perspective that may clear things up, let's say we have a generic extension method:
public static class Extenstions
{
// similar to but not quite the same as ('a -> ('a -> 'b) -> 'b)
public static V InvertOrder<T, U, V>(this T tVal, Func<T, U, V> f, U uVal)
{
return f(tVal, uVal);
}
}
C# extension methods allow us to do a (somewhat) similar thing as in the F# pipe and invert the order but we end up with lots of messy code lying around so it is not as practical as when using F#.
(4).InvertOrder((x, y) => x + y, 3)
I've found F# to be extremely fun to program with because of the flexibility and expresiveness of the language. As you can see, there are tons of ways of saying the same thing.
Next time we'll look at the power of the forward-pipe "push" operator and how we can use it to process groups of items.
Until next time,
Happy coding