iex(16)> maybe.(:true, :true)
{false, true}
iex(17)> maybe.(:true, :false)
{true, false}
iex(18)> maybe.(:false, :false)
{false, false}
iex(19)> maybe.(:false, :true)
{true, true}
I think I have a 2 clause version for this in my head I will take a closer look into it and tested when I’m at a proper computer and mobile my mobile phone
Yupp, my code does return the expected results.
I want to give others a chance to solve this as well and wait before releasing my solution to the public.
pattern match the args and return one of the tuples will be considered as a solution or I have to find another interesting solution
It starts as below:
maybe = &{ ... }
Nice… I’m far away from that.
edit
My current solution contains an if/2
, I’m not happy about it, but I can’t think of another solution right now.
I have a solution, where the function definition is as short as 12 characters
yes, it’s super short
Mine has 14 characters … EDIT: ok, there were two superfluous parentheses, now I am also at 12
SPOILER ALERT – SPOILER ALERT – SPOILER ALERT – SPOILER ALERT
SPOILER ALERT – SPOILER ALERT – SPOILER ALERT – SPOILER ALERT
SPOILER ALERT – SPOILER ALERT – SPOILER ALERT – SPOILER ALERT
Here is the answer:
maybe = &{ (&1 != &2), (&1 = &2)}
The interesting part is &1 = &2
, it is a pattern match not an equality!
in iex you get:
iex(27)> :true = :false
** (MatchError) no match of right hand side value: false
But same as the with
special form, when occurs a MatchError, the right hand side value is instead returned, then:
maybe.(:false, :true)
(:false != :true)
returns :true
(:false = :true)
returns :true
Actually, instead of &1=&2 you can just use &2 without the pattern match:
maybe = &{&1!=&2, &2}
Since the args in the problem are boolean, I went for xor
for the first element, which makes the solution a bit longer, but more restrictive about the input:
&{:erlang.xor(&1, &2), &2}
There has been no single correct reply to your question my shot of a correct answer is
maybe