[erlang-questions] Must and May convention
zxq9
zxq9@REDACTED
Fri Sep 29 15:17:28 CEST 2017
On 2017年09月29日 金曜日 08:53:38 Fred Hebert wrote:
> On 09/29, Richard A. O'Keefe wrote:
> >On 29/09/17 4:33 AM, Fred Hebert wrote:
> >
> >>As an example, Elixir has added the 'With' syntax:
> >>
> >> opts = %{width: 10, height: 15}
> >> with {:ok, width} <- Map.fetch(opts, :width),
> >> {:ok, height} <- Map.fetch(opts, :height),
> >> do: {:ok, width * height}
> >
> >How is this different from 'let'?
> >
> >There was a very old proposal for Erlang that
> >variables introduced between 'begin' ... 'end'
> >brackets should be local, so that this would be
> > begin
> > {ok,Width} = map:fetch(Opts, width),
> > {ok,Height} = map:fetch(Opts, height),
> > {ok, Width*Height}
> > end
> >If memory serves me, this was proposed about 25 years
> >ago, at about the same time that 'cond' was.
> >
>
> The distinction is in the control flow, rather than the scoping. With
> the `with' construct (and the reason why I compared it with monadic
> approaches), any value that represents an error returns and aborts the
> computation.
>
> The construct is rather equivalent to:
>
> case map:fetch(Opts, width) of
> {ok, Width} ->
> case map:fetch(Opts, height) of
> {ok, Height} ->
> {ok, Width*Height};
> {error, T} ->
> {error, T}
> end;
> {error, T} ->
> {error, T}
> end.
>
> The idea being that repeated conditionals based on the type of return
> (`{ok, Val} | {error, Term}`) could be abstracted over with a language
> construct.
>
> - The pipe (|>) can be the simplest one where a value is directly passed
> - the 'maybe' approach can be a branching based on `{ok,T}` or `{error,
> T}` that picks whether to keep calling the waiting functions or
> whether to return directly
>
> Variants could be imagined based on a requirement such as "connection is
> active", or "file has not reached EOF", or others. I don't know that
> they would be practical, but that's why I mentioned in earlier posts
> that the monadic approach (bind + return with say Haskell's do notation)
> could be an interesting model.
Why would this not be a pipeline function in the lists module?
It is actually done that way in more than a few inner project libs I've
worked with.
As an aside, I've always wondered why the lists module doesn't have
any pipelines, considering how often this sort of discussion comes up
and how quickly and cleanly it is solved inside various projects with
a pipeline function (or set of them that have different behaviors).
-Craig
More information about the erlang-questions
mailing list