Function definitions with literal parameters

I’m tinkering with groups, bitstrings and XOR. I don’t care about efficiency - but it’s always nice…

I create the type then I want functions dispatching on value :slight_smile:

@enum Bit zero one

⨁(zero, zero) = zero
⨁(zero, one) = one
⨁(one, zero) = one
⨁(one, one) = zero

In some universes this would work.

Is there a way of doing this in Julia?
If not can I express this neatly without an awful nested if-statement?

I think I could make zero = false, and one = true, in the @enum and use the built-in xor. But I wanted to see if I can do it as proposed.

Actually - shouldn’t I be doing it like:

⨁(a::𝔹, b::𝔹) = a == b ? zero : one

Advice please…

Cheers…

⨁ isn’t working as infix…

zero ⨁  one
ERROR: syntax: extra token "⨁" after end of expression
Stacktrace:
 [1] top-level scope
   @ none:1

You cannot dispatch on values, only on types.

The main way to do what you want would be to push your booleans to the type domain by wrapping them in Val (but then there’s no need for the Enum) or just constructing your own True/False singleton types. This is what Static.jl does.

(I’d just quickly caution that you should not follow this approach unless you know for sure that all input types (i.e. values here) are known statically - otherwise everything will be horribly type-unstable)

1 Like

@tchr thanks…

This is what happens when the unschooled watch people using proof-assistants :-). I was hoping I would break just enough to learn something.

I’ll go simple and use Booleans

MLStyle’s pattern matching and ADTs may help you

https://thautwarm.github.io/MLStyle.jl/latest/syntax/pattern.html

https://thautwarm.github.io/MLStyle.jl/latest/syntax/adt.html

2 Likes

Thanks very much I’ll have a go. Looks like I’ll learn something useful there…
Reminding me of Haskell

1 Like

I think I was also having some problems with unicode…
Now working OK. I’m happy with the type and the function, it is a clear expression of xor.

> @enum 𝔹 zero one

> ⊻(a::𝔹, b::𝔹) = a == b ? zero : one
⊻ (generic function with 1 method)

> @show (zero ⊻ one, one ⊻ one)
(zero ⊻ one, one ⊻ one) = (one, zero)

I’m remembering seeing dependent types from Idris: Gentle Introduction to Dependent Types with Idris