Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Erlang - Alternatives to function calls in guards etc

Tags:

erlang

I'm trying to learn Erlang, coming from a C++/Java background. This forces me to re-think all my methods.

Right now I'm trying to write something that returns the N first elements of a list. Right now it looks like this, although I can't call functions in guards or if expressions. What is the Erlang way of doing this?

take([Xh|Xr],N,Xn) ->
    if
        len(Xn) /= N -> take(Xr,N,app(Xh, Xn));
        len(Xn) == N -> Xn
    end.

I also tried calling the function before, but that didn't work either:

take([Xh|Xr],N,Xn) ->
   G = len(Xn);
    if
        G /= N -> take(Xr,N,app(Xh, Xn));
        G == N -> Xn
    end.
like image 538
Rickard Avatar asked Jan 18 '23 09:01

Rickard


1 Answers

Generally with this kind of problems, you need to switch to a recursive way of thinking instead of the iterative approach you're using. Here's what I would do:

take(List, N) ->
    take(List, N, []).
take(_List, 0, Acc) ->
    lists:reverse(Acc);
take([H|T], N, Acc) ->
    take(T, N - 1, [H|Acc]).

It's really common for people coming from languages that promote the iterative approach to try and shoehorn that approach into Erlang. The problem is that Erlang doesn't have the primitives for doing it that way since it's a functional language. So you're forced to do it the functional way, and in the end it's often the more elegant approach.

like image 100
Fylke Avatar answered Jan 21 '23 00:01

Fylke