Skip to content

Instantly share code, notes, and snippets.

View pragdave's full-sized avatar
🖍️
Alternating between Haskell and PDP-11 assembler

Dave Thomas pragdave

🖍️
Alternating between Haskell and PDP-11 assembler
View GitHub Profile
defmodule CheckDigit do
import Enum
@doc """
Determine if a sequence of digits is valid, assuming the last digit is
a Luhn checksum. (http://en.wikipedia.org/wiki/Luhn_algorithm)
"""
def valid?(numbers) when is_list(numbers) do
defrecord Poker.Card, face: 0, suit: "" do
def value(record) do
case record.face do
"A" -> 14
"K" -> 13
"Q" -> 12
"J" -> 11
"T" -> 10
int -> int
@pragdave
pragdave / gist:5997018
Created July 15, 2013 01:57
Two implementations of flatten/1
# The simplest version is probably to use list concatenation. However,
# this version ends up rebuilding the list at each step
defmodule UsingConcat do
def flatten([]), do: []
def flatten([ head | tail ]), do: flatten(head) ++ flatten(tail)
def flatten(head), do: [ head ]
end
# This version is more efficient, as it picks successive head values
# from a list, adding them to `result`. The trick is that we have to
@pragdave
pragdave / gist:6065316
Last active December 20, 2015 03:39
A simple DSL for gen_fsm. This generates regular gen_fsm functions (so, for example, each state/event combination is a separate function head)
defmodule Listen.NewFSM do
use Daves.Fsm, register: {:local, :listen_fsm},
initial_state: :start,
init_params: []
@timeout 3*1000
defrecord CallInfo, from: "", to: "", suspicious_segments: 0
defmodule Macros do
defmacro test(do: body) do
quote hygiene: [vars: false] do
def meth(a,b), do: unquote(body)
end
end
end
defmodule UseMacro do
import Macros
@pragdave
pragdave / test.ex
Created October 16, 2013 03:02
Description
defmodule Test do
def fred, do: 1
end
defimpl Enumerable, for: Bitmap do
import :math, only: [log: 1]
def reduce(bitmap, {:cont, acc}, fun) do
bit_count = Enum.count(bitmap)
_reduce({bitmap, bit_count}, { :cont, acc }, fun)
end
defp _reduce({_bitmap, -1}, { :cont, acc }, _fun), do: { :done, acc }
defmodule Reflect do
use Application.Behaviour
def run do
path = :code.lib_dir(:elixir, :ebin)
load_modules_in(path)
modules = for {name,_} <- :code.all_loaded,
Regex.match?(~r/^[A-Z]/, atom_to_binary(name)),
do: name
defmodule Bitmap do
defstruct value: 0
defimpl Access do
use Bitwise
def access(%Bitmap{value: value}, bit) do
if (value &&& (1 <<< bit)) == 0, do: 0, else: 1
end
end
defmodule Bitmap do
defstruct value: 0
end
defimpl Access, for: Bitmap do
use Bitwise
def access(%Bitmap{value: value}, bit) do
if (value &&& (1 <<< bit)) == 0, do: 0, else: 1
end