Packages

A simple Lisp interpreter implemented in Gleam. Features a REPL, basic Lisp functionality including arithmetic operations, list manipulation, conditionals, and variable definitions.

Current section

Files

Jump to
glisp src glisp@ast.erl
Raw

src/glisp@ast.erl

-module(glisp@ast).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch]).
-export([expr_to_string/1]).
-export_type([expr/0]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
?MODULEDOC(
"// Represents an expression in a Lisp-like language.\n"
"// Converts an expression to its string representation.\n"
).
-type expr() :: {atom, binary()} |
{number, integer()} |
{list, list(expr())} |
{builtin, fun((list(expr())) -> {ok, expr()} | {error, binary()})}.
-file("src/glisp/ast.gleam", 27).
?DOC(
"\n"
" This function returns a human-readable string that represents the given expression:\n"
" - Atoms are converted to their name\n"
" - Numbers are converted to their string representation\n"
" - Lists are converted recursively with elements joined by spaces and enclosed in parentheses\n"
" - Builtin functions are represented as \"#<builtin function>\"\n"
).
-spec expr_to_string(expr()) -> binary().
expr_to_string(Expr) ->
case Expr of
{atom, Name} ->
Name;
{number, N} ->
erlang:integer_to_binary(N);
{list, Elements} ->
Elements_str = begin
_pipe = gleam@list:map(Elements, fun expr_to_string/1),
gleam@string:join(_pipe, <<" "/utf8>>)
end,
<<<<"("/utf8, Elements_str/binary>>/binary, ")"/utf8>>;
{builtin, _} ->
<<"#<builtin function>"/utf8>>
end.