3. OCaml offspring
Created by MS Research
Mixed mode language
Functional
OO
Imperative (if you must)
Statically typed
4. Yay! Type inference
let x = 7
...also, immutable
let s = quot;kurtquot;
let pi = 3.142 So, really just “values”
5. let l = ['a';'b';'c';]
// char list or list<char>
Singly linked list
Still immutable!
let digits = [0..9]
// int list
6. IEnumerable<T>
let s = {1..10}
Useful for computing
// seq[1;2;3;...]
unbounded lists
7. let me = (quot;kurtquot;, 6.0)
Typed groups of values
// string * float
Can “hold” anything
let point3d = (0,0,0) Basically awesome
// int * int * int
8. let add x y = x + y
Like any other value
// int -> int -> int
More type inference
let eight = add 3 5 Returns last expression
// eight = 8
9. Look ma! Generics!
let group x y = (x,y)
// 'a -> 'b -> 'a * 'b Auto-generalization
10. let rec fib n =
if n < 2 then
n
Explicitly recursive
else
Tail recursion
(fib (n - 1)) +
(fib (n - 2))
11. type name = string
type number = int
type date = System.DateTime
type meeting =
| Personal of name * date
| Phone of number * date
let review = Personal(quot;Jasminequot;,System.DateTime.Now)
let call = Phone(8675309, System.DateTime.Now)
12. let what_to_do (m : meeting) =
match m with
| Personal(name,date) ->
printfn quot;Meeting with %s at %Aquot; name date
| Phone(phone, date) ->
printfn quot;Call %A at %Aquot; phone date
13. Functions are basic units of a program
We can mix them up in interesting ways
Less OO design patterns!
“Cheap” functions are good
Code is more expressive
14. let add3 = add 3
let add x y = x + y
// int -> int
// int -> int -> int
15. let even x = x % 2 = 0
// int -> bool
let numbers = [1..20]
let (|>) x f = f x // int list
let evens =
// 'a -> ('a -> 'b) -> 'b
numbers |>
List.filter even
// int list
16. List.fold_left
// ('b -> 'a -> 'b) ->
List.map
// 'b ->
// ('a -> 'b) ->
// 'a list ->
// 'a list ->
// 'b
// 'b list
[1..10] |> List.fold_left
[1..10] |> List.map add3
(fun acc x -> acc + x) 0
// [4;5;6;..;13]
// 55
17. 2520 is the smallest number that can be
divided by each of the numbers from 1 to 10
without any remainder.
What is the smallest number that is evenly
divisible by all of the numbers from 1 to 20?
- Project Euler
projecteuler.net
18. “Mutable” keyword
For real variables
There are imperative loops
Try not to use it too much
19. F# can be OO
Classes
Interfaces
Inheritance
Cross language work
“Hide” implementation
20. type OrderLine(n:string, q:int, p:float) =
let mutable currName = n
let mutable currQuantity = q
let mutable currPrice = p
new (name, price) = OrderLine(name, 1, price)
member x.Name
with get() = currName
and set name = currName <- name
member x.SubTotal with get() =
(Float.of_int quantity) * price
member x.OneMore() =
currQuantity <- currQuantity + 1
currQuantity
21. Why functional programming?
Easy to build incrementally
Simplified testing
Concurrency!
Imperative can be good too
At times, it’s wickedly fast
It’s what we know