Range Over Built in Erlang

Here we use range to sum the numbers in a slice. Arrays work like this too.

-module(example).
-export([main/0]).

main() ->
    %% Here we use `lists:sum/1` to sum the numbers in a list.
    %% Arrays in Erlang are represented as lists.
    Nums = [2, 3, 4],
    Sum = lists:sum(Nums),
    io:format("sum: ~p~n", [Sum]),

    %% `lists:foldl/3` can also be used to get the index and value.
    _ = lists:foldl(fun({Num, Index}, _) -> 
                        case Num of
                            3 -> io:format("index: ~p~n", [Index]);
                            _ -> ok
                        end
                    end, ok, lists:zip(Nums, lists:seq(1, length(Nums)))),

    %% `lists:foreach/2` iterates over key/value pairs in a map.
    KVs = #{"a" => "apple", "b" => "banana"},
    maps:map(fun(Key, Value) ->
                    io:format("~p -> ~p~n", [Key, Value])
              end, KVs),

    %% Display keys of a map
    maps:map(fun(Key, _) ->
                    io:format("key: ~p~n", [Key])
              end, KVs),

    %% `lists:map/2` with `string:chr/2` iterates over Unicode code points.
    %% The first value is the index and the second the code point.
    String = "go",
    _ = lists:map(fun(Char) ->
                        io:format("~p ", [Char])
                  end, string:to_integer(lists:seq(1, length(String)), String)),
    io:format("~n").

To run the program, save the code in example.erl, compile it using erlc, and then execute it in the Erlang shell.

$ erlc example.erl
$ erl -noshell -s example main -s init stop
sum: 9
index: 2
a -> apple
b -> banana
key: a
key: b
103 111

Now that we can run and build basic Erlang programs, let’s learn more about the language.