[erlang-questions] "prefix" ++ Rest = Something

Danil Zagoskin z@REDACTED
Wed Oct 25 18:12:29 CEST 2017


One can implement different ways of matching string against
prefix-as-binding:

7> Prefix = "hello ".
"hello "
8> {Prefix, Rest} = lists:split(length(Prefix), "hello world").
{"hello ","world"}
9> Rest.
"world"

10> Rest = lists:foldl(fun(C, [C|RestAcc]) -> RestAcc; (_, _) ->
error(badmatch) end, "hello world", Prefix).
"world"
11> lists:foldl(fun(C, [C|RestAcc]) -> RestAcc; (_, _) -> error(badmatch)
end, "help world", Prefix).
** exception error: badmatch
     in function  shell:apply_fun/3 (shell.erl, line 900)
     in call from lists:foldl/3 (lists.erl, line 1263)

12> MatchPref = fun MatchPref([], SRest) -> SRest; MatchPref([C|Pref],
[C|SRest]) -> MatchPref(Pref, SRest); MatchPref(_, _) -> error(badmatch)
end.
#Fun<erl_eval.36.99386804>
13> Rest = MatchPref(Prefix, "hello world").
"world"
14> Rest = MatchPref(Prefix, "help world").
** exception error: badmatch

So it should be possible to implement a syntactic sugar for Prefix ++ Rest
= String.
I suppose one can do that even for function/case clauses (but that would be
more tricky).

Seems like parse_transform would be enough for a proof-of-concept. In this
case even no OTP patch is required.

On Wed, Oct 25, 2017 at 9:56 AM, Stefan Hellkvist <hellkvist@REDACTED>
wrote:

> Hi,
>
> Erlang has this syntactic sugar for matching string prefixes (
> http://erlang.org/doc/reference_manual/expressions.html#id80508) where
> you can do:
>
> "prefix" ++ Rest = "prefixsomething"
>
> , which would bind Rest to "something" in this case.
>
>
> I'm curious why however it is ok to do:
>
> 1> "prefix" ++ Rest = "prefixsomething".
> "prefixsomething"
> 2> Rest.
> "something"
>
>
> but it is not ok to do:
>
> 1> Prefix = "prefix".
> "prefix"
> 2> Prefix ++ Rest = "prefixsomething".
> * 1: illegal pattern
>
>
> Is it because this syntactic sugar is transformed more or less as a
> preprocessing step where the value of Prefix needs to be known, or why else
> is "Prefix ++ Rest = Something" not allowed even when Prefix is bound?
>
> /Stefan
>
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions
>
>


-- 
Danil Zagoskin | z@REDACTED
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20171025/786e9889/attachment.htm>


More information about the erlang-questions mailing list