operator overloading outside the type
Dukc
ajieskola at gmail.com
Wed Apr 2 12:19:44 UTC 2025
On Tuesday, 1 April 2025 at 13:06:21 UTC, Mengu wrote:
> Wny can't we just treat operators as functions or vice versa?
> Haskell does this perfectly:
>
> ```haskell
> ghci> :i (+)
> type Num :: * -> Constraint
> class Num a where
> (+) :: a -> a -> a
> ...
> -- Defined in ‘GHC.Num’
> infixl 6 +
> ghci> 1 + 1
> 2
> ghci> (+) 1 1
> 2
> ```
Well, user-definable order of evaluation would mean that you
can't figure out order of evaluation in expressions anymore at
the parsing phase, since `infix`/`infixl`/`infixr` operators
couldn't be processed before the semantic phase (especially if
they are mixed in!). Non-expression syntaxes wouldn't be
affected, though, and you could still always figure out what's
part of an expression and what's not.
But we could have operators to be just syntactic sugar over
functions, just with a fixed order of evaluation. For user
defined types, this is almost how it already works after all. `a
+ b` is the same as `a.opBinary!"+"(b)`, or
`b.opBinaryRight!"+"(a)`. We'd simply have to allow those to call
module-scope functions as per normal UFCS rules, and maybe define
members/`object.d` intrinsic functions so that
`5.opBinary!"+"(5)` would work.
More information about the Digitalmars-d
mailing list