[erlang-questions] Ternary Like Operation Idiom in Erlang

Michael Turner leap@REDACTED
Thu Dec 3 10:08:45 CET 2009


>Thanks to Dale's version I came up with this.
>
>F = fun(T) -> case re:split(T,"=",[{return,list}]) of [K] -> {K,true};
>[K,V] -> {K,V} end end.

Cute, but with whitespace trailing after the "=", you get {key, " "},
which might not be the desired behavior.  Moreover, an embedded "=" in
the Value part (e.g, key='a=1' or something ridiculous like that) will
cause it to fail, which also might not be desired behavior.  Getting
close, though.

The following

Fm = fun(T) ->
   case re:split(string:strip(T),"=",[{return,list}]) of
    [K] -> {K, true};
    [K | V] -> {K, string:join (V, "=")}
   end
end.

seems to cover those cases.  I'm assuming you don't care that there's
no whitespace stripped from the left end of the V string.  But maybe you
do.

It's admittedly now too long to a candidate for "idiomatic Erlang."  I
wonder if it could be significantly shorter, but still robust?  I'd
love to pursue this further, but I just got an urgent call about some
gig that involves biting the heads off of live chickens.


-michael turner


On 12/2/2009, "Jarrod Roberson" <jarrod@REDACTED> wrote:

>Thanks to Dale's version I came up with this.
>
>F = fun(T) -> case re:split(T,"=",[{return,list}]) of [K] -> {K,true};
>[K,V] -> {K,V} end end.
>
>in action
>
>Eshell V5.7.3  (abort with ^G)
>1> F = fun(T) -> case re:split(T,"=",[{return,list}]) of [K] ->
>{K,true}; [K,V] -> {K,V} end end.
>#Fun<erl_eval.6.13229925>
>2> F("key").
>{"key",true}
>3> F("key=value").
>{"key","value"}
>4> F("key=").
>{"key",[]}
>5>
>
>________________________________________________________________
>erlang-questions mailing list. See http://www.erlang.org/faq.html
>erlang-questions (at) erlang.org
>
>


More information about the erlang-questions mailing list