nedwed
nedwed

Reputation: 243

Erlang - Can one use Lists:append for adding an element to a string?

Here is my function that parses an addition equation.

expr_print({num,X}) -> X; 
expr_print({plus,X,Y})->
             lists:append("(",expr_print(X),"+",expr_print(Y),")").

Once executed in terminal it should look like this (but it doesn't at the moment):

>math_erlang: expr_print({plus,{num,5},{num,7}}).
>(5+7)

Upvotes: 0

Views: 406

Answers (1)

mpm
mpm

Reputation: 3584

Actually one could do that, but it would not work the way wish in X in {num, X} is a number and not string representation of number.

Strings in Erlang are just lists of numbers. And if those numbers are in wright range they can be printed as string. You should be able to find detail explenation here. So first thing you wold like to do is to make sure that call to expr_print({num, 3}). will return "3" and not 3. You should be able to find solution here.

Second thing is lists:append which takes only one argument, list of list. So your code could look like this

expra_print({num,X}) ->
    lists:flatten(io_lib:format("~p", [X]));
expr_print({plus,X,Y})->
     lists:append(["(", expr_print(X),"+",expr_print(Y), ")"]).

And this should produce you nice flat string/list.

Another thing is that you might not need flat list. If you planning to writing this to file, or sending over TCP you might want to use iolist, which are much easier to create (you could drop append and flatten calls) and faster.

Upvotes: 1

Related Questions