Skip to content

Instantly share code, notes, and snippets.

View expede's full-sized avatar
Highly caffeinated

Brooklyn Zelenka expede

Highly caffeinated
View GitHub Profile
Interactive Elixir (1.6.4) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> use Witchcraft
iex(2)> alias Algae.Maybe
# With a Just
iex(5)> monad %Maybe.Just{} do
...(5)> a <- Maybe.Just.new(1)
...(5)> b <- Maybe.Just.new(2)
...(5)> return(a + b)
@expede
expede / witchcraft_monadic_do.ex
Last active May 20, 2020 15:54
Witchcraft Monadic Do Notation Primer
# ========
# NOTATION
# ========
# Control.Monad (Haskell) Bind
>>=
# Witchcraft.Chain.bind (Elixir)
>>>
{-
Vectors are fixed-length data structures
They're written in this format: `Vect length type`
ex. `Vect 3 Int` could represent [1,2,3], but not [1,2] or ['a', 'b', 'c']
-}
concat : Vect lengthX a -> Vect lengthY a -> Vect (lengthX + lengthY) a
concat Nil ys = ys
concat (x :: xs) ys = x :: app xs ys
@expede
expede / IntegerProps.hs
Last active October 21, 2016 17:07
IntegerProps
x == x -- Reflixivity
x * 0 == 0 -- Origin
x * 0 * 0 == 0 -- Idempotence
x + 0 == x -- Additive identity
x / 1 == x -- Divisive identity
x * 1 == x -- Multiplicative identity
@expede
expede / MonadLaws.hs
Last active October 12, 2016 09:32
Monad laws
return a >>= f == f a -- Left Identity
m >>= return == m -- Right Identity
(m >>= f) >>= g == m >>= (\x -> f x >>= g) -- Associativity
-- ...plus all applicative functor laws
# =====================
# Explicit branch names
# =====================
branch OtherFile.read("./existing_file.txt"),
value_do: String.length,
exception_do: fn %{message: msg} -> msg end.()
# => 1000
branch OtherFile.read("./missing.file"),
OtherFile.read("./existing_file.txt")
~> fn text ->
text
|> String.length
|> fn x -> x / 2 end.()
end.()
|> to_tagged_status
#=> {:ok, 500}
# `ok` alias for tagged_status
search_result = find_book(title: title)
case search_result do
page = %Page{} -> render(page)
%Ecto.MultipleResultsError{} when is_series(title) ->
%Book.SeriesAreNotBooksError{
message: "#{title} is a series, not a book.",
title: title,
series: search_result,
plug_status: 422
}
use Exceptional
OtherFile.read("./existing_file.txt") ~> String.length
# 19
OtherFile.read("./missing.file") ~> String.length
# %OtherFile.NotFoundError{
# message: "File not found at ./missing.file",
# path: "./missing.file"
# }
# Hypothetical rewrite of `File.read`
# Not the lack of a `OtherFile.read!` (with a bang),
# but we get the same effect with the caller via `>>>`
# Success
iex> OtherFile.read("./existing_file.txt")
"I'm a little teapot short and stout ..."
# Error
# Note that this returns an Exception struct as a value