Created
March 22, 2018 13:03
-
-
Save rflechner/c8e18b49a0506f92fc157b20c3d06070 to your computer and use it in GitHub Desktop.
training fsharp 1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
printfn "hello world" | |
open System.Runtime.InteropServices | |
let mutable name = "toto" | |
name <- "tata" | |
let display text = | |
printfn "%s" text | |
let add a b = | |
a + b | |
add 1 1 | |
let addOne = add 1 | |
let addTwo = add 2 | |
let addTree = addOne >> addTwo | |
addTree 2 | |
// comparaison | |
2 = 4 | |
2 = 2 | |
// types | |
type Hotel = | |
{ Name : string | |
Stars : int } | |
let hotel1 = { Name="Paris Hotel" ; Stars = 3 } | |
let hotel2 = { Name="Ladef Hotel" ; Stars = 4 } | |
let hotel1bis = { Name="Paris Hotel" ; Stars = 3 } | |
hotel1 = hotel2 | |
hotel1 = hotel1bis | |
match hotel1 with | |
| { Name="Paris Hotel" } -> printfn "popo" | |
| { Name=n } when n.Contains "hotel" -> printfn "tutu" | |
| _ -> printfn "toto" | |
let addStars n hotel = | |
{ hotel with Stars=hotel.Stars+n } | |
let hotel1Bigger = hotel1 |> addStars 2 | |
let ``hotel1 bigger`` = addStars 2 hotel1 | |
printfn "%b" (hotel1Bigger = hotel1) | |
// tuples | |
let t1 = (1, 2, "toto") | |
let t2 = (1, (true, 4), "toto") | |
let (a,b,c) = t1 | |
match t1 with | |
| (1,_,_) -> printfn "perdu" | |
| (a,b,c) when a > 3 -> printfn "gagné" | |
| _ -> printfn "encore un coup" | |
let n = 5 | |
match n with | |
| _ when n % 2 = 0 -> printfn "even" | |
| _ -> printfn "odd" | |
let (|Even|Odd|) n = | |
if n % 2 = 0 | |
then Even | |
else Odd | |
match 4 with | |
| Even -> printfn "pair" | |
| Odd -> printfn "impair" | |
let n2 = Some "toto" | |
let n3 : string option = None | |
match n2 with | |
| Some n -> printfn "name: %s" n | |
| None -> printfn "Unknown" | |
let (|MultipleOf|_|) n x = | |
if n % x = 0 | |
then Some () | |
else None | |
//(|MultipleOf|_|) 2 3 | |
let multipleOf n x = x % n = 0 | |
let (|Fizz|Buzz|FizzBuzz|Other|) x = | |
if multipleOf 15 x | |
then FizzBuzz | |
elif multipleOf 5 x | |
then Buzz | |
elif multipleOf 3 x | |
then Fizz | |
else Other | |
let fizzBuzz x = | |
match x with | |
| Fizz -> printfn "fizz" | |
| Buzz -> printfn "buzz" | |
| FizzBuzz -> printfn "fizzbuzz" | |
| Other -> printfn "%d" x | |
fizzBuzz 3 | |
[1 .. 20] |> List.iter fizzBuzz | |
let (|Fizz|_|) x = if multipleOf 3 x then Some x else None | |
let (|Buzz|_|) x = if multipleOf 5 x then Some x else None | |
let fizzBuzz' = function | |
| Fizz (Buzz _) -> printfn "fizzbuzz" | |
| Fizz _ -> printfn "fizz" | |
| Buzz _ -> printfn "buzz" | |
| x -> printfn "%d" x | |
[1 .. 20] |> List.iter fizzBuzz' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment