Skip to content

Instantly share code, notes, and snippets.

@amir734jj
Created February 13, 2023 05:16
Show Gist options
  • Save amir734jj/349371699050067aa251eb63d88fff52 to your computer and use it in GitHub Desktop.
Save amir734jj/349371699050067aa251eb63d88fff52 to your computer and use it in GitHub Desktop.
Practicing array in fsharp
open System
type 'a List =
| Nil
| Cons of 'a * 'a List
let single = Cons(12, Cons(2, Nil))
let rec last ls =
match ls with
| Nil -> Nil
| Cons (v, Nil) -> v
| Cons (_, rest) -> last rest
let rec concat l r =
match l with
| Nil -> r
| Cons (v, Nil) -> Cons(v, r)
| Cons (v, rest) -> Cons(v, concat rest r)
let rec split source left right pivot =
match source with
| Nil -> (left, right)
| Cons (v, rest) ->
if (v <= pivot) then
split rest (Cons(v, left)) right pivot
else
split rest left (Cons(v, right)) pivot
let rec quickSort source =
match source with
| Nil -> Nil
| Cons (v, rest) ->
let left, right = split rest Nil Nil v
concat (quickSort left) (concat (Cons(v, Nil)) (quickSort right))
let convert arr =
let rec reverse arr result =
match arr with
| Nil -> result
| Cons(v, rest) -> reverse rest (Cons(v, result))
let rec convert_helper arr result =
match arr with
| [] -> result
| v :: rest -> convert_helper rest (Cons(v, result))
reverse (convert_helper arr Nil) Nil
let to_s arr =
let rec to_s_helper ls =
match ls with
| Nil -> ""
| Cons (v, Nil) -> $"{v}"
| Cons (v, rest) -> $"{v}, " + to_s_helper rest
"[" + to_s_helper arr + "]"
let rec map fn arr =
match arr with
| Nil -> Nil
| Cons (v, rest) -> Cons(fn v, map fn rest)
let rec reduce fn acc arr =
match arr with
| Nil -> acc
| Cons (v, rest) -> reduce fn (fn acc v) rest
let rec filter fn arr =
match arr with
| Nil -> Nil
| Cons (v, rest) -> if (fn v) then Cons(v, filter fn rest) else filter fn rest
let source = (convert [ 5; 4; 3; 2; 1 ])
Console.WriteLine("source: " + (to_s source))
let sorted = quickSort source
Console.WriteLine("sorted(source): " + (to_s sorted))
let incremented = map (fun x -> x + 1) sorted
Console.WriteLine("incremented(sorted): " + (to_s incremented))
let evens = filter (fun x -> x % 2 = 0) incremented
Console.WriteLine("even(incremented): " + (to_s incremented))
let inc_sum = reduce (fun acc v -> acc + v) 0 evens
Console.WriteLine("sum(evens): " + (inc_sum |> string))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment