Skip to content

Instantly share code, notes, and snippets.

@hodzanassredin
Created January 8, 2021 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hodzanassredin/e65c5d13956cb8d5533e1b76fcb2ccfa to your computer and use it in GitHub Desktop.
Save hodzanassredin/e65c5d13956cb8d5533e1b76fcb2ccfa to your computer and use it in GitHub Desktop.
Basick arithmetic opearations in fsharp
type Number = Zero | Succ of Lazy<Number>
let swap f a b = f b a
let toOption = function
| Zero -> None
| r -> Some(r)
let rec fold (f:('State -> 'State)) (state: 'State) (n: Number) : 'State =
match n with
| Zero -> state
| Succ(n) -> fold f (f state) n.Value
let rec unfold (f:('State -> 'State option)) (state:'State) : Number =
match (f state) with
| None -> Zero
| Some(state) -> Succ(lazy(unfold f state))
let inc a = Succ(lazy(a))
let dec = function
| Zero -> None
| Succ(n) -> Some(n.Value)
let sum a b = fold inc a b
let minus a b = fold (Option.bind dec) (Some(a)) b
let mul a b = fold (sum a) Zero b //foreach b add a to acc, acc is zero initially
let div a b = unfold (swap minus b) a //while we can minus b from acc inc res , acc initially is a
let pow a b = fold (mul a) (inc Zero) b
let log a b = unfold ((swap div b >> toOption) ) a
let number = unfold (fun n -> if n = 0 then None else Some(n-1))
let eval = fold (fun n ->
//printfn "evaluation %d" n
n + 1) 0
let evalOpt o = match o with None -> -1 | Some(o) -> eval o
let check f n1 n2 opName =
f (number n1) (number n2) |> eval |> printfn "%d%s%d=%d" n1 opName n2
let checkOpt f n1 n2 opName =
f (number n1) (number n2) |> evalOpt |> printfn "%d%s%d=%d" n1 opName n2
check sum 1 3 "+"
checkOpt minus 3 1 "-"
checkOpt minus 3 3 "-"
checkOpt minus 3 5 "-"
check mul 3 2 "*"
check mul 3 5 "*"
check mul 3 0 "*"
check div 4 2 "/"
check div 3 2 "/"
check div 2 2 "/"
check div 1 2 "/"
check pow 1 2 " pow "
check pow 2 2 " pow "
check pow 2 3 " pow "
check pow 2 4 " pow "
check log 4 2 " log "
check log 8 2 " log "
check log 16 2 " log "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment