Saya sedang membaca buku Erlang Programming. Nah ini adalah solusi dari Exercise 2-3: Simple Pattern Matching. Pertanyaan aslinya adalah sebagai berikut:
Write a module boolean.erl that takes logical expressions and Boolean values (represented as the atoms true and false) and returns their Boolean result. The functions you write should include b_not/1, b_and/2, b_or/2, and b_nand/2. You should not use the logical constructs and, or, and not, but instead use pattern matching to achieve your goal.Test your module from the shell. Some examples of calling the exported functions in your module include:
bool:b_not(false) => true
bool:b_and(false, true) => false
bool:b_and(bool:b_not(bool:b_and(true, false)), true) => true
The notation foo(X) => Y means that calling the function foo with parameter X will result in the value Y being returned. Keep in mind that and, or, and not are reserved words in Erlang, so you must prefix the function names with b_.
Hint: implement b_nand/2 using b_not/1 and b_and/2.
Solusinya adalah:
-module(bool).
-export([b_not/1, b_and/2, b_or/2, b_nand/2]).
b_not(X) -> X == false.
b_and(X,Y) -> {true, true} == {X,Y}.
b_or(X,Y) -> b_not({false, false} == {X,Y}).
b_nand(X,Y) -> b_not(b_and(X,Y)).
-export([b_not/1, b_and/2, b_or/2, b_nand/2]).
b_not(X) -> X == false.
b_and(X,Y) -> {true, true} == {X,Y}.
b_or(X,Y) -> b_not({false, false} == {X,Y}).
b_nand(X,Y) -> b_not(b_and(X,Y)).
Ada yang punya solusi lebih baik?