AnchovyLegend
AnchovyLegend

Reputation: 12538

Erlang basics: Syntax error at compile time

I am very new to Erlang and I am trying to compile my first program and I am getting a syntax error at compile time.

The syntax error I am getting points to line 2 filter_inside undefined. Also syntax error on last line before X.

functions.erl

-module(functions).
-export([filteri/2]).

filteri(_, []) -> 
                    []; 
filteri(P,[X|XS]) ->
                    [(map(P) X)|filteri P XS].

I have been trying to debug for about an hour now with no success, I was wondering if someone can help me identify what it is about the code that is making it fail to compile.

Many thanks in advance!

Upvotes: 2

Views: 320

Answers (2)

Kijewski
Kijewski

Reputation: 26022

Erlang separates clauses by semicolons ;.

Statements are separated by commas ,.

Just use []; in the 5th line.

The last line is broken, too. To prepend an element Head to a list Tail use [Head|Tail] including the brackets.

A function call looks like Fun(Arg1, Arg2, ...).

Erlang is case sensitive. x is an atom (you may see it as a string constant), whereas X is the variable X.

Easier to use than explicit recursion is list comprehension [Fun(X) || X <- XS] (or [Fun(X) || X <- XS, Predicate(X)]).

I guess you could use

filter_inside(Fun, XSS) ->
    [ [Fun(X) || X <- XS] || XS <- XSS ].

In your solution you can use this as your last line:

[list:map(P, X)|filter_inside(P, XS)].  % Mind the function call syntax.

Erlang reported a problem in the -export line because the function contained an error, so the name is unknown.

One further comment: Use filter_inside(_, []) as the last clause for speed up.

Upvotes: 4

Vinod
Vinod

Reputation: 2243

Last Line [(map(P) X)|filter_inside P XS]. should be [P(X) | filter_inside(P, XS)]. Syntax needs to be corrected. You are looking for map apply and predicate to get back the result i.e. implement lists:map.

Ex: lists:map(fun(A)->A*2 end, [1,2,3,4,5]). to get result equivalent as [2,4,6,8,10]

Then in Erlang you may also write like this to utilize tail recursion optimization:

-module(functions).
-export([filter_inside/2]).

filter_inside(P,L) ->
    filter_inside(P,L, []).

filter_inside(_, [], Acc) -> 
    lists:reverse(Acc); 
filter_inside(P,[X|XS], Acc) ->
    filter_inside(P, XS,  [P(X) | Acc]).

Upvotes: 2

Related Questions