Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang pattern matching with functions

As Erlang is an almost pure functional programming language, I'd imagine this was possible:

case X of
    foo(Z) -> ...
end.

where foo(Z) is a decidable-invertible pure (side-effect free) bijective function, e.g.:

foo(input) -> output.

Then, in the case that X = output, Z would match as input.

Is it possible to use such semantics, with or without other syntax than my example, in Erlang?

like image 974
Pindatjuh Avatar asked Jul 05 '11 17:07

Pindatjuh


People also ask

What is pattern-matching in Erlang?

Pattern matching is used for assigning values to variables and for controlling the flow of a program. Erlang is a single assignment language, which means that once a variable has been assigned a value, the value can never be changed. Pattern matching is used to match patterns with terms.

How do you call a function in Erlang?

7.2 Function CallsCalls to local or external functions (foo(), m:foo()) are the fastest calls. Calling or applying a fun (Fun(), apply(Fun, [])) is just a little slower than external calls. Applying an exported function (Mod:Name(), apply(Mod, Name, [])) where the number of arguments is known at compile time is next.

What is pattern-matching in F#?

Pattern matching is ubiquitous in F#. It is used for binding values to expressions with let , and in function parameters, and for branching using the match..with syntax.

What type of variables are used in Erlang?

Variables can contain alphanumeric characters, underscore and @. Variables are bound to values using pattern matching. Erlang uses single assignment, that is, a variable can only be bound once. The anonymous variable is denoted by underscore (_) and can be used when a variable is required but its value can be ignored.


2 Answers

No, what you want is not possible.

To do something like this you would need to be able to find the inverse of any bijective function, which is obviously undecidable.

like image 151
sepp2k Avatar answered Oct 01 '22 17:10

sepp2k


I guess the reason why that is not allowed is that you want to guarantee the lack of side effects. Given the following structure:

case Expr of
    Pattern1 [when GuardSeq1] ->
        Body1;
    ...;
    PatternN [when GuardSeqN] ->
        BodyN
end

After you evaluate Expr, the patterns are sequentially matched against the result of Expr. Imagine your foo/1 function contains a side effect (e.g. it sends a message):

foo(input) ->
  some_process ! some_msg,
  output.

Even if the first pattern wouldn't match, you would have sent the message anyway and you couldn't recover from that situation.

like image 41
Roberto Aloi Avatar answered Oct 01 '22 16:10

Roberto Aloi