Skip to content

Instantly share code, notes, and snippets.

-module(records).
-compile(export_all).
-record(foo, {bar = "baz"}).
-define(make_record_to_list(Record),
fun(Val = #Record{}) ->
Fields = record_info(fields, Record),
[_Tag| Values] = tuple_to_list(Val),
all_msg(Acc) ->
receive
X ->
all_msg([X|Acc])
after
1 ->
Acc
end.
@Gustav-Simonsson
Gustav-Simonsson / gist:1501514
Created December 20, 2011 13:06
proplist_to_record
-define(proplist_to_record(Record),
fun(PropList) ->
[_Tag | Defaults] = tuple_to_list(#Record{}),
Fields = record_info(fields, Record),
list_to_tuple([Record | [proplists:get_value(F, PropList, D)
|| {F, D} <- lists:zip(Fields, Defaults)]])
end).
subs(String, Ints) ->
{Intervals, _} = lists:mapfoldl(fun(E, A) -> L = A + E, {{A, L - 1}, L} end, 1, Ints),
[string:sub_string(String, Start, Stop) || {Start, Stop} <- Intervals].
-module(foo).
-compile(export_all).
printer(Text, Num_times, Time_between) ->
[begin io:format(Text), timer:sleep(Time_between) end
|| _ <- lists:seq(1, Num_times)].
main() ->
spawn(?MODULE, printer, ["Hello~n", 30, 10]),
spawn(?MODULE, printer, ["World~n", 40, 15]),
to_proplist_meta(Meta,Rs) ->
lists:map(
fun(Res) ->
Elems = fun(Ele, Cnt) ->
V = if element(Cnt,Res) == null -> undefined;
true -> element(Cnt,Res) end,
{{Ele,V},Cnt+1}
end,
{Base,BaseCnt} = lists:mapfoldl(Elems, 1, hd(Meta)),
{Other,_} = lists:mapfoldl(
@Gustav-Simonsson
Gustav-Simonsson / gist:3756004
Created September 20, 2012 13:41
gen_server template
-module(template).
-behaviour(gen_server).
%% API
-export([start_link/0]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
@Gustav-Simonsson
Gustav-Simonsson / gist:4564310
Created January 18, 2013 12:35
migrate with rpc
5> el_pl:is_sublist([apa], [apa, varg]).
true
6> meck:new(el_pl).
ok
7> meck:expect(el_pl, is_sublist, fun(List1, List2) ->
rpc:call('nodeattmigreratill@vargarna.nu', el_pl, is_sublist, [List1, List2]) end).
ok
8>
@Gustav-Simonsson
Gustav-Simonsson / gist:4564450
Created January 18, 2013 13:07
migrate_module
migrate_module(Module, Function, Arity, RemoteNode) ->
%% Assume Arity is 2, general arity solution needed.
RPCFun = fun(Arg1, Arg2) ->
rpc:call(RemoteNode, Module, Function, [Arg1, Arg2]) end,
meck:new(Module),
meck:expect(Module, Function, RPCFun).
-module(crack).
-export([crack/0]).
-compile(export_all).
-define(CHAR_LIST, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW").
crack() ->
TryLength = 5,
MD5Hash = crypto:md5("12345"),