Contents | < Browse | Browse >
4L. unification (<=>)
---------------------
Unification allows a totally different style of programming
that will be familiar to you if you're used to either Logic
(ProLog), equational or functional (Miranda/Gofer/Haskell)
programming. Most of us when using structures/arrays whatever
are used to get values from it by selection ("." and "[]"),
in these languages however pattern matching is used.

in E:

exp <=> uni_exp

exp can be any expression, but in v3 it's only really useful
if it somehow is a pointer to a list. uni_exp is the pattern
that is used to match exp. All constants in uni_exp much
match to values in exp, variables are set to their respective
values. if something doesn't match, no variables get a value,
and the expression has the result FALSE. otherwise TRUE.
example:

a:=[1,2,3]
...
IF a <=> [1,x,y] THEN ...

this will succeed with x=2 and y=3. If list a were to be another
lenght than 3, the match would fail too. The fact that a is a list
in the first place is something you need to assure by yourself, EC
simply tries to fit the uni_exp on whatever value it gets as exp.
examples of FALSE:

a <=> [1,x]		-> wrong list-len
a <=> [1,4,x]		-> 4=2 fails
'bla' <=> [1,2]		-> unpredictable result / crash ?

The fun thing with unification is that you can do very complex matches,
and that if you take the first field or so as a constant telling what the
structure is, you have a nice form of dynamic typing. And, all the time
without using PTRs!

a slightly nicer example:

[BLA,[1,'burp'],['bla',"bla"]] <=> [BLA,[1,x],y]

binds:

x='burp', y=['bla',"bla"]

or even:

IF myexp <=> [PLUS,[MUL,a,1],[SUBS,[PLUS,c,d],e]] THEN RETURN a+c+d-e

maybe a silly example, but one could imagine doing complex stuff
like this in a compiler's code-optimizer. it equals this traditional code:

IF ListLen(myexp)=3
  IF myexp[]=PLUS
    IF ListLen(dummy:=myexp[1])=3
      IF (dummy[]=MUL) AND (dummy[2]=1)
        a:=dummy[1]
        IF ListLen(dummy:=myexp[2])=3
          IF dummy[]=SUBS
            e:=dummy[2]
            IF ListLen(dummy2:=dummy[1])=3
              IF dummy2[]=PLUS
                c:=dummy2[1]
                d:=dummy2[2]
                RETURN a+c+d-e
              ENDIF
            ENDIF
          ENDIF
        ENDIF
      ENDIF
    ENDIF
  ENDIF
ENDIF

only then a bit more optimal. As you see there's a lot of expressive
power involved in unification as compared to traditional selection-based
programming.

For now, the only thing allowed in unification are untyped lists,
(integer) constants, variables and LISP-Cells (see  9I  for that).
The future will see this expanded with strings, typed-lists/objects,
and even expressions [!]