3

I'm trying to define the logical operation exclusive or as a two-variable function. I can't use constants, type annotations or if-then-else. I believe I'm supposed to do it by using logic operators, but am lost on how I'm supposed to write out a function just using those! So far I have

fun xor(a,b) = a orelse b andalso not(a andalso b).

How am I supposed to return a true value from this point?

4

1 回答 1

4

首先,所以你不需要记住的相对优先级和关联性andalsoorelse我会使用更多的括号:

fun xor(a,b) = (a orelse b) andalso not(a andalso b);
- map xor [(true, true), (true, false), (false, true), (false, false)];
val it = [false,true,true,false] : bool list

您的错误是您的表达式关联如下

a orelse (b andalso not(a andalso b));

sml 中没有“返回”的概念。只有表达式,它们被评估为值,然后在其他表达式中使用。

(a orelse b) andalso not(a andalso b)

计算为 type 的值bool。您可以使用该结果进行进一步的计算:

if xor(foo, bor) then 1 else 2
于 2013-09-06T20:58:22.080 回答