Advertisement
Guest User

Demo

a guest
Jun 13th, 2014
310
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 2.06 KB | None | 0 0
  1. #light
  2.  
  3. let add a b c =
  4.   let ab = a + b
  5.   printfn "%d" ab
  6.   c - ab
  7.  
  8. //Using non-light you can write the same thing like this:
  9. let add a b c =
  10.   let ab = a + b in // 'in' keyword specifies where the binding (value 'ab') is valid
  11.   printfn "%d" ab;  // ';' is operator for sequencing expressions
  12.   c - ab;;          // ';;' is end of a function declaration
  13.  
  14. // IMMUTABILITY
  15. let x = 1
  16. x <- 2
  17. x=2
  18.  
  19. let y = 1.0
  20. let z = [1; 2; 3]
  21.  
  22. // FUNCTIONS
  23. let sqr x = x * x
  24.  
  25. let sqr 5
  26.  
  27. let Add x y =
  28.         x + y
  29.  
  30. let AddFn = fun x y -> x + y
  31.  
  32. //Add 5 5
  33. //AddFn 1 2
  34.  
  35. let Add1 = Add 1.0
  36.  
  37. //Add1 3
  38.  
  39. // IMPERATIVE STYLE
  40. let sumOfSqr nums =
  41.     let mutable acc = 0   // assigning to a location in mmry
  42.     for x in nums do
  43.        acc <- acc + sqr x // pushing sth in this location
  44.     acc
  45.  
  46. // FUNCTIONAL STYLE
  47. // mathematican write code like that
  48. let rec sumOfSqrF nums =
  49.     match nums with
  50.     | [] -> 0
  51.     | h::t -> sqr h + sumOfSqrF t
  52.  
  53. let rec sumOfSqrF2 nums =
  54.     nums
  55.     |> Seq.map sqr   // pipeline thing
  56.     |> Seq.sum
  57.  
  58. sumOfSqrF2 []
  59.  
  60.  
  61. //Higher-order f
  62. let twice f x = f(f x)
  63.  
  64. twice sqr 3
  65.  
  66. // TYPES
  67. type User = { Username: string; Age : int }
  68.  
  69. let me = { Username = "monika"; Age = 21 }
  70.  
  71. let GetAge user
  72.     user.Age
  73.  
  74. let tup = ("Text", 1)
  75.  
  76. let someNumber = Some 5
  77. let noNumber = None
  78.  
  79. type Color =
  80.     | Red = 1
  81.     | Green = 2
  82.     | Blue = 3
  83.  
  84. // PATTERN MATCHING
  85.  
  86. match tup with
  87.    | ("Text", _) -> printfn "Success"
  88.    | (_, 1)
  89.    | (_, 2) ->printfn "Other tuple"
  90.    | _ -> printfn "Bad idea"
  91.  
  92. let parse = false
  93.  
  94. match tup, parse with
  95.    | _, false -> printfn "-1"
  96.    | _, true -> printfn "+1"
  97.  
  98. match me with
  99.    | { Username = "monika"; Age = _ } -> printfn "It's me"
  100.    | _ -> printfn "Have you met me?"
  101.  
  102. let numbers = [1; 2; 3; 4]
  103.  
  104. match numbers with
  105.    | [ w; x; y; z] -> printfn "numbers had 4 elements"
  106.    | _ ->  printfn "whatever"
  107.  
  108.  
  109. //  UNITS OF MEASURE
  110.  
  111. [<Measure>] type Metre
  112.  
  113. let x = 10<Metre>
  114.  
  115. let Add5Meters x =
  116.     x + 5<Metre>
  117.  
  118. Add5Meters x
  119.  
  120. Add5Meters 5
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement