Skip to content

Instantly share code, notes, and snippets.

@Xdeon
Xdeon / stream.sml
Created October 24, 2020 18:30
A simple stream implementation in sml
(* a stream is a thunk that when called produces a pair
#1 of the pair will be of type 'a and #2 of the pair will be another stream *)
(* can only have recursive type using datatype binding *)
datatype 'a StreamPair = Stream of 'a * (unit -> 'a StreamPair)
(* a ones stream *)
fun ones () = Stream (1, ones)
(* a fibonacci number stream *)
fun fibs () =
@Xdeon
Xdeon / gf.erl
Created July 26, 2020 01:37
frequency server based on gen_server
%% Based on code from
%% Erlang Programming
%% Francecso Cesarini and Simon Thompson
%% O'Reilly, 2008
%% http://oreilly.com/catalog/9780596518189/
%% http://www.erlangprogramming.org/
%% (c) Francesco Cesarini and Simon Thompson
-module(gf).
-behaviour(gen_server).
@Xdeon
Xdeon / frequency_front.erl
Created July 14, 2020 06:42
frequency server scaling up with front-end router
-module(frequency_front).
-export([start/0, allocate/0, deallocate/1, stop/0]).
-export([init/0]).
%% API
allocate() ->
send_receive(allocate).
deallocate(Freq) ->
send_receive({deallocate, Freq}).
1> % first compile frequency using contents of frequency2.erl
1> c(frequency).
{ok,frequency}
2> frequency:start().
true
3> frequency:allocate().
{ok,10}
4> frequency:allocate().
{ok,11}
-module(exceptions).
-export([eval/2, wrap/2]).
% simple model of arithmetical expressions, like
% {add, {num, 0}, {mul, {num,1}, {var,a2}}}
% environment gives value of a variable:
% [ {a,2}, {b,1} ]
eval(_Env, {num, N}) -> N;
@Xdeon
Xdeon / frequency.erl
Created July 11, 2020 02:31
frequency server with exceptions
-module(frequency).
-export([start/0, allocate/0, deallocate/1, stop/0, init/0]).
start() ->
Pid = spawn(?MODULE, init, []),
register(?MODULE, Pid),
Pid.
allocate() ->
send_receive(allocate).
@Xdeon
Xdeon / echo.erl
Created July 8, 2020 08:44
naive supervisor
-module(echo).
-export([listener/0]).
listener() ->
receive
{Pid, M} ->
io:format("~w echoed.~n", [M]),
Pid ! M,
listener()
end.
@Xdeon
Xdeon / frequency_hardened.erl
Last active July 11, 2020 02:12
frequency server hardened with links
-module(frequency_hardened).
-export([start/0, allocate/0, deallocate/1, stop/0, init/0]).
start() ->
Pid = spawn(?MODULE, init, []),
register(?MODULE, Pid),
Pid.
allocate() ->
?MODULE ! {request, self(), allocate},
@Xdeon
Xdeon / frequency.erl
Created July 7, 2020 06:25
frequency server revised
-module(frequency).
-export([start/0, allocate/0, deallocate/1, stop/0, clear/0, clear_with_print/0, init/0]).
start() ->
Pid = spawn(?MODULE, init, []),
register(?MODULE, Pid),
Pid.
%% Add clear at beginning of each API call to eliminate unexpected messages in mailbox
%% better use combination of erlang:make_ref() and "let it fail"
-module(frequency).
-export([start/0, init/0]).
start() ->
Pid = spawn(?MODULE, init, []),
register(?MODULE, Pid),
Pid.
init() ->
Frequencies = {get_frequencies(), []},