Skip to content

Instantly share code, notes, and snippets.

View hrajchert's full-sized avatar
🎯
Focusing

Hernan Rajchert hrajchert

🎯
Focusing
View GitHub Profile
new :: forall a r. a -> ST r (STRef r a)
-- 1) forall a r.
-- 2) a ->
-- 3) ST r (...)
-- 4) (STRef r a)
type Request = { url :: String, verb :: String }
-- We define a full object
defaultReq :: Request
defaultReq = { url: "", verb: "GET"}
-- And then use it to create a new one, with a changed property
googleReq :: Request
googleReq = defaultReq { url = "http://www.google.com" }
-- { url: "http://www.google.com", verb: "GET" }
nine :: Int
nine = 9
-- Compiler error: The value nine has been defined multiple times
nine = 8
foreign import length :: forall h a. STArray h a -> Int
mutableQSortBy :: forall a. (a -> a -> Ordering) -> Array a -> Array a
mutableQSortBy cmp inmutableArr = run (withArray mutableComputation inmutableArr) where
mutableComputation :: forall h. STArray h a -> ST h Unit
mutableComputation arr = sort 0 (length arr - 1) where
swap :: Int -> Int -> ST h Unit
swap i j = do
-- Read both values
qsortBy :: forall a. (a -> a -> Ordering) -> Array a -> Array a
qsortBy cmp xs = case uncons xs of
Nothing -> []
Just { head, tail } ->
let
small = filter (\x -> (cmp x head) == LT) tail
mid = filter (\x -> (cmp x head) == EQ) tail
large = filter (\x -> (cmp x head) == GT) tail
in
qsortBy cmp small <> mid <> [head] <> qsortBy cmp large
import Data.Array (filter, uncons)
qsort :: Array Int -> Array Int
qsort xs = case uncons xs of
Nothing -> []
Just { head, tail } ->
let
small = filter (\x -> x < head) tail
mid = filter (\x -> x == head) tail
large = filter (\x -> x > head) tail
type Ordering = 'LT' | 'GT' | 'EQ';
function qsortBy <T>(cmp: (a: T, b: T) => Ordering, arr: ReadonlyArray<T>): ReadonlyArray<T> {
if (arr.length === 0) {
return [];
}
const [head, ...tail] = arr;
const small = tail.filter(x => cmp(x, head) == 'LT');
function mutableQSortBy<T> (cmp: (a: T, b: T) => Ordering, arr: ReadonlyArray<T>): ReadonlyArray<T> {
function swap(arr: Array<T>, i: number, j: number) {
const temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
function partition(maxLeft: number, minRight: number, arr: Array<T>): number {
let iPivot = maxLeft;
let iLeft = maxLeft;
let iRight = minRight;
function qsort (arr: ReadonlyArray<number>): ReadonlyArray<number> {
if (arr.length === 0) {
return [];
}
const [head, ...tail] = arr;
const small = tail.filter(x => x < head);
const mid = tail.filter(x => x == head);
const large = tail.filter(x => x > head);
return [...qsort(small), ...mid, head, ...qsort(large)];
}
mutable :: _
mutable = run do
-- left and right :: STRef r Int
left <- Ref.new 0
right <- Ref.new 6
let
condition = do
l <- Ref.read left
r <- Ref.read right