Skip to content

Instantly share code, notes, and snippets.

View sasa1977's full-sized avatar

Saša Jurić sasa1977

View GitHub Profile
defmodule Lambda do
defmacro l(code) do
make_fun(arity(code), code)
end
defmacro l(arity, code) do
make_fun(arity, code)
end
defp make_fun(arity, code) do
defmodule Lambda do
defrecord ParseResponse, code: nil, arity: 0 do
def new_list, do: new(code: [])
def push(response, this) do
this.
update_arity(max(response.arity, &1)).
update_code([response.code | &1])
end
@sasa1977
sasa1977 / manipulating_hierarchy.ex
Last active December 14, 2015 05:09
Different styles of manipulating hierarchy in Elixir
defmodule Fp do
defmodule Company do
defrecordp :company, employees: HashDict.new
defrecordp :employee, [:id, :name]
def merge_employee(company(employees: employees), employee(id: employee_id) = employee) do
company(company, employees: Dict.put(employees, employee_id, employee))
end
def new, do: company()
defmodule RecordHelper.DynGenerator do
defmacro __using__(_) do
generate_macros
end
defp generate_macros do
Enum.map(1..20, fn(i) -> def_macro(args(i)) end)
end
defp def_macro(args) do
defrecord LazySeq, [:state, :generator, :limit, {:step, 0}] do
def next(LazySeq[] = current) do
{value, new_state} = current.generator.(current.state)
{value, current.state(new_state).update_step(&1 + 1)}
end
end
defimpl Enum.Iterator, for: LazySeq do
def count(LazySeq[] = lseq), do: lseq.limit
defmodule MyLc do
def next({_, :stop}, _), do: []
def next([], _), do: []
def next([current | next], fun) do
[fun.(current) | next(next, fun)]
end
def next({iter, {current, next}}, fun) do
@sasa1977
sasa1977 / xmerl_demo.ex
Last active July 26, 2023 10:07
Simple xmerl usage demo in Elixir
defmodule XmlNode do
require Record
Record.defrecord :xmlAttribute, Record.extract(:xmlAttribute, from_lib: "xmerl/include/xmerl.hrl")
Record.defrecord :xmlText, Record.extract(:xmlText, from_lib: "xmerl/include/xmerl.hrl")
def from_string(xml_string, options \\ [quiet: true]) do
{doc, []} =
xml_string
|> :binary.bin_to_list
|> :xmerl_scan.string(options)
@sasa1977
sasa1977 / flatten.ex
Created July 15, 2013 09:23
list flattening
defmodule Flatten do
def flatten(deep_list), do: collect_flattened([], deep_list)
defp collect_flattened(acc, []), do: acc
defp collect_flattened(acc, [h | t]) do
acc
|> collect_flattened(t)
|> flatten(h)
end
defrecord Person, id: nil, name: nil
defrecord ParserState, persons: [], current_person: nil
defmodule TestXmerlSax do
def xml do
%b(
<doc>
<person id="1">Joe Armstrong</person>
<person id="2">José Valim</person>
</doc>
defmodule Dict.Behaviour do
# It is assumed that the client module implements following functions:
# size/1, fetch/2, put/3, dict_delete/2
#
# And that it defines Enumerable implementation
defmacro __using__(_) do
quote do
# Following are exact copies of HashDict: