Advertisement
pavelperc

sem2

Sep 11th, 2018
652
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.49 KB | None | 0 0
  1. // let x = 1::2::3::[]
  2. let x = [1;2;3]
  3.  
  4.  
  5. let rec sum = function
  6.   | [] -> 0
  7.   | x::xs -> x+sum xs
  8.  
  9. let len L =
  10.     let rec len' acc = function
  11.    | [] -> acc
  12.    |_::xs -> len' (acc+1) xs
  13.     len' 0 L
  14.  
  15. len [1..100]
  16.  
  17. let rec fmin = function
  18. | [x] -> (x, [])
  19. | x::xs ->
  20.    let (z,zs) = fmin xs
  21.    if z>x then (x,xs)
  22.    else (z, x::zs)
  23.  
  24. fmin [3;1;2]
  25.  
  26. let rec sort = function
  27. | [] -> []
  28. | [x] -> [x]
  29. | L -> let (x,xs) = fmin L
  30.       x::sort xs
  31.  
  32. sort [1;4;2;5;3]
  33.  
  34. let rec fold f i = function
  35.  | [] -> i
  36.  | x::xs -> f x (fold f i xs)
  37.  
  38. // fold is like reduce
  39. let sum = fold (+) 0
  40.  
  41. sum [1..100]
  42.  
  43. let minel = fold min (System.Int32.MaxValue)
  44.  
  45. minel [2;1;3]
  46.  
  47. let length L = fold (fun _ acc->acc+1) 0 L
  48.  
  49. length [2;1;3;4]
  50.  
  51. let minmax L = fold (fun x (mi,ma) -> (min mi x, max ma x)) (List.head L, List.head L) L
  52.  
  53. minmax [1;4;3;2]
  54.  
  55.  
  56. let minel L = List.reduce min L
  57.  
  58. let sum = List.reduce (+)
  59.  
  60.  
  61. List.map (fun x->x*2) [1;2;3]
  62.  
  63. // created own map
  64. let map f L = fold (fun x acc -> (f x)::acc) [] L
  65.  
  66. map ((*)2) [1;2;3]
  67.  
  68.  
  69. [1..100]
  70. |> List.map (fun x -> x*x)
  71. |> sum
  72.  
  73. // prime numbers:
  74.  
  75. let flip f x y = f y x
  76.  
  77. [2..100] |> List.filter ((%)3 >> (<)0)
  78.  
  79. let rec primes = function
  80.  | [] -> []
  81.  | x::xs -> x::(primes(List.filter (flip(%)x >> (<)0) xs))
  82.  
  83.  
  84. primes [2..100]
  85.  
  86. List.map2 (*) [1;2;3] [4;5;6]
  87.  
  88. [1..10] |> List.iter (printf "%d ")
  89.  
  90. let L = [1..100]
  91.  
  92. // never do this!!! n^2 complexity!!:
  93. for i = 0 to List.length(L)-1 do printf "%d " L.[i]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement