Advertisement
Guest User

fun with f#

a guest
Mar 24th, 2014
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 2.05 KB | None | 0 0
  1. // Learn more about F# at http://fsharp.net
  2. // See the 'F# Tutorial' project for more help.
  3. exception Empty
  4.  
  5. let hd list =
  6.     match list with
  7.     |   [] -> raise Empty
  8.     |   hd::tl -> hd
  9.  
  10. let tl list =
  11.     match list with
  12.     |   [] -> raise Empty
  13.     |   hd::tl -> tl
  14.  
  15. let zero x y z =
  16.     x + y + z
  17.  
  18. let one x y =
  19.     (y,x)
  20.    
  21. let two (a, b) (c, d) =
  22.     (a, b, c, d)
  23.  
  24. let three f g (a : int, b : int, c : int) =
  25.     (f a |> g, f b |> g, f c |> g)
  26.  
  27. let four =
  28.     fun a b c -> a + b + c
  29.    
  30. let five =
  31.     ()
  32.  
  33. let six arr =
  34.      (arr |> Array.min, arr |> Array.averageBy (fun elem -> float elem), arr |> Array.max)
  35.  
  36. let seven arr =
  37.     arr |> Array.sumBy (fun elem -> float elem)
  38.  
  39. let rec eight n =
  40.     match n with
  41.     | 0 -> 1
  42.     | _ -> n * eight (n - 1)
  43.  
  44. let rec eightSimple n =
  45.     List.fold (fun acc elem -> acc * elem) 1 [1 .. n]
  46.  
  47. let nine list index =
  48.     List.nth list index
  49.  
  50. let rec nineRecursive list index =
  51.     let rec foo list index i =            
  52.         match i = index with
  53.             |   false -> foo (tl list) index (i + 1)
  54.             |   true -> hd list
  55.     foo list index 0
  56.  
  57. let ten list n =
  58.     let rec foo array n i =
  59.         match i < n with
  60.             |   true -> hd array + foo (tl array) n (i + 1)
  61.             |   false -> 0
  62.     foo list n 0
  63.  
  64. let tenWithCheats list n =
  65.     Seq.fold (fun acc elem -> (acc + elem)) 0 (list |> Seq.take(n))
  66.  
  67. let eleven list n =
  68.     ten (List.rev list) n
  69.  
  70. [<EntryPoint>]
  71. let main argv =
  72.     printfn "zero 2 3 5 = %i" (zero 2 3 5)
  73.     printfn "one 3 5 = %A" (one 3 5)
  74.     printfn "two (2 3) (5 4) = %A" (two (2,3) (5, 4))
  75.     printfn "three fn x => x + 1 fm x => x * 2 (1, 2, 3) = %A" (three (fun x -> x + 1) (fun x -> x * 2) (1, 2, 3))
  76.     printfn "eight 3 = %i" (eightSimple 3)
  77.     printfn "nine [1 .. 25] 15 = %A" (nineRecursive [1 .. 25] 15)
  78.     printfn "tenRetared [1 .. 10] 5 = %i" (tenWithCheats [1 .. 10] 5)
  79.     printfn "eleven [1 .. 10] 5 = %i " (eleven [1 .. 10] 5)
  80.     System.Console.ReadLine()
  81.     0 // return an integer exit code
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement