# [erlang-questions] chained functions

Wed Jan 25 11:59:50 CET 2012

```Hello.

On 25.1.2012 08:53, Bengt Kleberg wrote:
> For things like this (seq/2 below) there is also lists:foldl/3 and
> lists:foldr/3

But they're not the same. seq/2 supports early termination
(see its last clause) whereas lists:foldl/3 traverses all
elements in the list. Thus, you would still have to wrap a
call to lists:foldl/3 in an exception trapping code and use
throw(Result) in the fold fun to terminate prematuraly
(i.e. implement your seq2/2 using lists:foldl/3). I found
the original seq/2 (much) easier to understand. Or have I
miss anything?

Just my 2c,

> On Tue, 2012-01-24 at 22:24 +0100, Gianfranco Alongi wrote:
>> What an error!
>> Should be:
>>
>> If all your functions F_1 ... F_K have the type
>>
>>   F(Input) ->   {ok,Result} | {error,Reason}
>>
>> then I would probably write a small sequencer as
>>
>> seq(X,[]) ->
>>     X;
>> seq({ok,Result},[ F | T ]) ->
>>    seq(F(Res),T);
>> seq({error,Reason},_) ->
>>    {error,Reason}.
>>
>> And call it like
>>
>> seq({ok,Initial},[ fun F_1, ..., fun F_K ])
>>
>> /G
>>
>> (And that's why you don't write your emails in a haste before bed!!!)
>>
>> On Tue, Jan 24, 2012 at 10:17 PM, Gianfranco Alongi
>> <>  wrote:
>>> If all your functions F_1 ... F_K have the type
>>>
>>> F({ok,Result} | {error,Reason} ) ->   {ok,Result} | {error,Reason}
>>>
>>> then I would probably write a small sequencer as
>>>
>>> seq({ok,Result},[ F | T ]) ->
>>>   seq(F(Res),T);
>>> seq(Error,T) ->
>>>   Error.
>>>
>>> And call it like
>>>
>>> seq({ok,Initial},[ fun F_1, ..., fun F_K ])
>>>
>>> I always try to tag values, so you can use it to determine flow control.
>>>
>>> Cheers
>>> G
>>>
>>> On Tue, Jan 24, 2012 at 8:31 PM, Reynaldo Baquerizo
>>> <>  wrote:
>>>>
>>>> A friend of mine asked:
>>>>
>>>> ##
>>>> If you have functions that return {ok, Result} | {error, Reason}
>>>> how do you chained them? So that you have:
>>>>
>>>> w(x(y(z(...))))
>>>>
>>>> without building a staircasing. Something that would be done in Haskell
>>>> ##
>>>>
>>>> I would probably go for:
>>>>
>>>> x({ok, Value}) ->
>>>>   NewValue =<do something with Value>,
>>>>   {ok, NewValue};
>>>> x({error, Reason}) ->
>>>>   {error, Reason}.
>>>>
>>>> in each function
>>>>
>>>> which brings me other question, when do you tag return values?
>>>>
>>>> I tend to only use tagged return values with impure functions, were an
>>>> error is more likely due to side effects.
>>>>
>>>> --
>>>> Reynaldo
>>>> _______________________________________________
>>>> erlang-questions mailing list
>>>>
>>>> http://erlang.org/mailman/listinfo/erlang-questions
>> _______________________________________________
>> erlang-questions mailing list
>>
>> http://erlang.org/mailman/listinfo/erlang-questions
>
> _______________________________________________
> erlang-questions mailing list
>
> http://erlang.org/mailman/listinfo/erlang-questions
>
>

```