Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #light
- let add a b c =
- let ab = a + b
- printfn "%d" ab
- c - ab
- //Using non-light you can write the same thing like this:
- let add a b c =
- let ab = a + b in // 'in' keyword specifies where the binding (value 'ab') is valid
- printfn "%d" ab; // ';' is operator for sequencing expressions
- c - ab;; // ';;' is end of a function declaration
- // IMMUTABILITY
- let x = 1
- x <- 2
- x=2
- let y = 1.0
- let z = [1; 2; 3]
- // FUNCTIONS
- let sqr x = x * x
- let sqr 5
- let Add x y =
- x + y
- let AddFn = fun x y -> x + y
- //Add 5 5
- //AddFn 1 2
- let Add1 = Add 1.0
- //Add1 3
- // IMPERATIVE STYLE
- let sumOfSqr nums =
- let mutable acc = 0 // assigning to a location in mmry
- for x in nums do
- acc <- acc + sqr x // pushing sth in this location
- acc
- // FUNCTIONAL STYLE
- // mathematican write code like that
- let rec sumOfSqrF nums =
- match nums with
- | [] -> 0
- | h::t -> sqr h + sumOfSqrF t
- let rec sumOfSqrF2 nums =
- nums
- |> Seq.map sqr // pipeline thing
- |> Seq.sum
- sumOfSqrF2 []
- //Higher-order f
- let twice f x = f(f x)
- twice sqr 3
- // TYPES
- type User = { Username: string; Age : int }
- let me = { Username = "monika"; Age = 21 }
- let GetAge user
- user.Age
- let tup = ("Text", 1)
- let someNumber = Some 5
- let noNumber = None
- type Color =
- | Red = 1
- | Green = 2
- | Blue = 3
- // PATTERN MATCHING
- match tup with
- | ("Text", _) -> printfn "Success"
- | (_, 1)
- | (_, 2) ->printfn "Other tuple"
- | _ -> printfn "Bad idea"
- let parse = false
- match tup, parse with
- | _, false -> printfn "-1"
- | _, true -> printfn "+1"
- match me with
- | { Username = "monika"; Age = _ } -> printfn "It's me"
- | _ -> printfn "Have you met me?"
- let numbers = [1; 2; 3; 4]
- match numbers with
- | [ w; x; y; z] -> printfn "numbers had 4 elements"
- | _ -> printfn "whatever"
- // UNITS OF MEASURE
- [<Measure>] type Metre
- let x = 10<Metre>
- let Add5Meters x =
- x + 5<Metre>
- Add5Meters x
- Add5Meters 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement