问题
I have question about SKI-Combinators.
Can XOR (exclusive or) be expressed using S
and K
combinators only?
I have
True = Cancel
False = (Swap Cancel)
where
Cancel x y = K x y = x
Swap: ff x y = S ff x y = ff y x
回答1:
Booleans
Your question is a bit unclear on the details, but it seems that what you mean is that you have the following representation of booleans:
T := K
F := S K
This works because it means the following reductions hold:
T t e => t
F t e => e
in other words, b t e
can be interpreted as IF b THEN t ELSE e
.
XOR in terms of IF _ THEN _ ELSE _
So given this framework, how do we implement XOR? We can formulate XOR as an IF
expression:
xor x y := IF x THEN (not y) ELSE y = (IF x THEN not ELSE id) y
which can be eta-reduced to
XOR x := IF x THEN not ELSE id = x not id
Some function combinators
We have id = SKK
as standard, and not
can be expressed as flip
, since flip b t e = b e t = IF b THEN e ELSE t = IF (not b) THEN t ELSE e
. flip it self is quite involved but doable as
flip := S (S (K (S (KS) K)) S) (KK)
Now we just need to figure out a way to write a function that takes x
and applies it on the two terms NOT
and ID
. To get there, we first note that if we set
app := id
then
app f x = (id f) x = f x
and so,
(flip app) x f = f x
We are almost there, since everything so far shows that
((flip app) id) ((flip app) not x) = ((flip app) not x) id = (x not) id = x not id
The last step is to make that last line point-free on x
. We can do that with a function composition operator:
((flip app) id) ((flip app) not x) = compose ((flip app) id) ((flip app) not) x
where the requirement on compose
is that
compose f g x = f (g x)
which we can get by setting
compose f g := S (K f) g
Putting it all together
To summarize, we got
xor := compose ((flip app) id) ((flip app) not)
or, fully expanded:
xor = S (K ((flip app) id)) ((flip app) not)
= S (K ((flip app) (SKK))) ((flip app) flip)
= S (K ((flip SKK) (SKK))) ((flip SKK) flip)
= S (K (((S (S (K (S (KS) K)) S) (KK)) SKK) (SKK))) (((S (S (K (S (KS) K)) S) (KK)) SKK) (S (S (K (S (KS) K)) S) (KK)))
来源:https://stackoverflow.com/questions/37119381/can-xor-be-expressed-using-ski-combinators