how to get [3,5] from [ ["3"], ["5"] ] - it works! i used string:to_integer

Per Hedeland <>
Sun Aug 7 19:25:44 CEST 2005


MEENA SELVAM <> wrote:
>
>FinalList = fun(X) -> {I} = string:to_integer(X),
>                      I
>             end.
> 
> lists:map(FinalList, [["3"],["5"]]).

You want the list_to_integer/1 BIF (documented in the erlang(3) man
page):

1> F = fun([S]) -> list_to_integer(S) end. 
#Fun<erl_eval.6.39074546>
2> lists:map(F, [["3"],["5"]]).
[3,5]

>> my doubt is, io_lib:format writes on terminal, but
>> does it return the character that is printed or some
>> other return values.
>> 
>> is there anything similar to sprintf in c, in
>> formatting and moving the output of to a list?

io_lib:format() doesn't write on the terminal, and is indeed similar to
sprintf() in C - but what you'd want for this (in the general case)
would rather be the opposite, something similar to sscanf() in C, which
is io_lib:fread().

Unfortunately the documentation for fread() in the io_lib(3) man page is
wrong, claiming that it uses the same format codes as io:format().
Writing an integer with io:format() is done with the 'w' format code,
but that doesn't work to read an integer with fread(), and the 'd'
format code that is needed doesn't work with io:format(). Luckily you
have the source.

5> io_lib:fread("~d", "42").
{ok,"*",[]}

A somewhat surprising result, but due to the shell's "helpfulness" in
using 'p' for printouts - it is actually correct:

6> io:format("~w~n", [v(-1)]).
{ok,[42],[]}
ok

>> > I need to extract the first element of every
>> tuple,
>> > in
>> > a tuplelist in the format[a,b]
>> > 
>> > what I have is:
>> > 
>> > FirElem = fun(X)->
>> >             {C,_} = X,
>> >             C
>> >           end.
>> > 
>> >
>>
>lists:map(FirElem,[{["3"],["red"]},{["5"],["yellow"]}]).

7> f(F).
ok
8> F = fun({[S],_}) -> list_to_integer(S) end.
#Fun<erl_eval.6.39074546>
9> lists:map(F,[{["3"],["red"]},{["5"],["yellow"]}]).
[3,5]

--Per Hedeland



More information about the erlang-questions mailing list