Advertisement
AlexG2230954

Functional programming

Mar 10th, 2024
1,682
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 1.20 KB | None | 0 0
  1. type Seq<'a> = Getter of (unit -> ('a * Seq<'a>) option)
  2.  
  3. let PrintSeq (seq: Seq<'a>) =
  4.     let rec _step getter =
  5.         match getter() with
  6.         | None -> ()
  7.         | Some(el, Getter(nextGetter)) ->
  8.             printf "%A, " el
  9.             _step nextGetter
  10.    
  11.     match seq with
  12.     | Getter(f) -> _step f
  13.  
  14. let Map seq f =
  15.     let rec _step getter () =
  16.         match getter() with
  17.         | None -> None
  18.         | Some(el, Getter(nextGetter)) ->
  19.             Some(f el, Getter(_step nextGetter))
  20.    
  21.     match seq with
  22.     | Getter(g) -> Getter(_step g)
  23.  
  24. let Reduce seq f =
  25.     let rec _step value getter =
  26.         match getter() with
  27.         | None -> value
  28.         | Some(el, Getter(nextGetter)) ->
  29.             _step (f value el) nextGetter
  30.  
  31.     match seq with
  32.     | Getter(g) ->
  33.         match g() with
  34.         | None -> None
  35.         | Some(el, Getter(getter)) -> Some(_step el getter)
  36.  
  37. // Sequences
  38.  
  39. let Range a b c : Seq<int> =
  40.     let rec _getter x () =
  41.         if x >= b then None
  42.         else Some(x, Getter(_getter (x + c)))
  43.     Getter(_getter a)
  44.  
  45. let rng = Range 1 5 1
  46. let x = Reduce rng (+)
  47.  
  48. match x with
  49. | Some(y) -> printfn "%d" y
  50. | None -> printfn "neon"
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement