Skip to content
CCPEDIAby Unity Nodes
App Development

Extending the Daml math operators

2 posts166 viewsLast activity Sep 2022

  1. cohen.avrahamOP

    G-d willing

    Hello, I would like to extend the capabilities of math operators in such a way that it will automatically convert different numerical values. For example, I would like to extend the + operator so when I add to Decimal value an Int Value I won’t need to call a specific function that receives a Decimal and Int arguments and returns a Decimal.

    The same I would like to do to the == operator (The Eq typeclass) so when I compare a Decimal 5.0 to Int 5 it will return True. Like so:

      let fiveD = 5.0 : Decimal
      let fiveI = 5
    
      debug $ fiveD == fiveI
    

    Thanks,

  2. bernhard

    (+) and (==) are defined in Prelude. Modifying prelude is possible, but I’d strongly advise against it as if you get it wrong, a lot of things break.

    You’d need to use a language extension like NoImplicitPrelude and then import your own prelude everywhere. You’d need to define new versions of the Eq and Additive typeclasses that don’t define == : a -> a -> Bool and + : a -> a -> a, but == : a -> b -> Bool and + : a -> b -> c, and then write instances for those typeclasses to both cover the standard + and == and your new uses.

    A better approach would be to define your own typeclass

    class CompatibleNumerics a b c where
      (+') : a -> b -> c
      (==') : a -> b -> Bool
    

    Then write lots of instances and use +' and ==' as where appropriate.