Today’s Erlang Thursday takes a look at user_default
.
I stumbled across this when trying to verify what version of c/1
and l/1
was used when called in the shell, and came across shell_default documentation.
It mentioned that if there are functions that we would like to have available in the shell, we can have a module user_default
and specify its location in our .erlang
file in our home directory.
Since I have a fizzbuzz example in Erlang handy, lets start out with that for our user_default
module as proof that we can get it working. And we’ll put it in tmp
under our home directory.
-module(user_default). -export([fizzbuzz/1]). fizzbuzz(N) -> Translations = lists:map(fun translate/1, lists:seq(1, N)), lists:foreach(fun(Item) -> io:format("~s~n", [Item]) end, Translations). translate(N) when N rem 3 =:= 0 andalso N rem 5 =:= 0 -> 'FizzBuzz'; translate(N) when N rem 3 =:= 0 -> 'Fizz'; translate(N) when N rem 5 =:= 0 -> 'Buzz'; translate(N) -> integer_to_list(N).
Let’s open up a new .erlang
file in our home directory, and add the following line, pointing to the location of the user_default
file we just created.
code:load_abs("tmp/user_default").
If you already have a .erlang
file, then the call to code:load_abs/1 for the user_default
module must be the first line in the file.
Time to ensure both files are saved, and open up the erlang shell, and try calling fizzbuzz/1
.
$ erl Erlang/OTP 17 [erts-6.2.1] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace] Eshell V6.2.1 (abort with ^G) 1> fizzbuzz(20). ** exception error: undefined shell command fizzbuzz/1 2> q(). ok
Doesn’t seem to be working as advertised. Realizing that this is load_abs
, and user_default
is a new module, the error is probably because there is no file to load. Let’s go compile the module using erlc
, and try again.
$ cd tmp/ $ erlc user_default.erl $ ls user_default.* user_default.beam user_default.erl $ cd ..
We now have a BEAM file there, so let’s startup the Erlang shell again and try to call fizzbuzz/1
.
$ erl Erlang/OTP 17 [erts-6.2.1] [source] [64-bit] [smp:8:8] [async-threads:10] [hipe] [kernel-poll:false] [dtrace] Eshell V6.2.1 (abort with ^G) 1> fizzbuzz(20). 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz ok 2>
And it works! We now have fizzbuzz/1
available for use in the shell without needing to specify a module.
For more information on the .erlang configuration file, check out the Configuration section of the Erlang Getting Started documentation.
–Proctor