[erlang-questions] Run external program with arguments

Torbjorn Tornkvist <>
Wed Nov 14 19:06:26 CET 2007


Anders Dahlin wrote:
> Except foldr will produce a reversed result, so foldl is a better choice.

Sorry, but you are wrong!
----------------------------
-module(aaa).
-compile(export_all).

r(Data,Seperator) ->
    lists:foldr(fun(X,[]) -> X; (X,Acc) -> X++Seperator++Acc end, "", Data).

l(Data,Seperator) ->
    lists:foldl(fun(X,[]) -> X; (X,Acc) -> X++Seperator++Acc end, "", Data).
---------------------------------
1> aaa:r(["a","b","c"], ".").
"a.b.c"
2> aaa:l(["a","b","c"], ".").
"c.b.a"
------------------------------------
To make use of foldl you need to write l/2 like this:

l2(Data,Seperator) ->
    lists:foldl(fun(X,[]) -> X; (X,Acc) -> Acc++Seperator++X end, "", Data).

3> aaa:l2(["a","b","c"], ".").
"a.b.c"
---------------------------------------
But this is actually worse, since append usually recurse on its left
argument which in this case is Acc which will grow for each iteration.

I guess there is a reason why Haskell define fold as a synonym for foldr.

Cheers, Tobbe

> 
> Brgds,
> /A
> 
> Torbjorn Tornkvist wrote:
>> Bob Ippolito wrote:
>>> The easiest way is to perform shell quoting over the command you
>>> want... take a look at mochiweb_util:cmd_port/2.
>>>
>>> http://mochiweb.googlecode.com/svn/trunk/src/mochiweb_util.erl
>> Hm...that join function. Couldn't it be written like:
>>
>> %%-----------------------------------------------------------------------------
>> %% @spec implode(Str::string(), Sep::string()) -> string()
>> %%
>> %% @doc  split text at first occurence of Char (Char is not include in
>> Before
>> %%       or After parts)
>> %%
>> %%  Example:  implode(["a","b","c"], ".") => "a.b.c"
>> %%
>> %%
>> @end------------------------------------------------------------------------
>> implode(Data, Seperator) when is_list(Data) andalso is_list(Seperator) ->
>>     lists:foldr(fun(X,[]) -> X; (X,Acc) -> X++Seperator++Acc end, "", Data).
>>
>>
>> Cheers, Tobbe
>>
>>> -bob
>>>
>>> On 11/14/07, Alexander Zhukov <> wrote:
>>>> Hi!
>>>>
>>>> Is there a way to run an external program from Erlang program with
>>>> arguments?
>>>>
>>>> I like to be able to write something like this:
>>>>
>>>> Port = open_port({spawn, Ext_prog_name}, [stream, {args, ["-c", "file", "-d"]}]),
>>>>
>>>> but so far I can't find a way to run a program with arguments.
>>>>
>>>> Yes, I know I can write a wrapper script but I do not like such an
>>>> approach.
>>>>
>>>> --
>>>> Alexander Zhukov
>>>> _______________________________________________
>>>> erlang-questions mailing list
>>>> 
>>>> http://www.erlang.org/mailman/listinfo/erlang-questions
>>>>
>> _______________________________________________
>> erlang-questions mailing list
>> 
>> http://www.erlang.org/mailman/listinfo/erlang-questions




More information about the erlang-questions mailing list