I was trying to implement some El Gamal cryptography in plutus, basic verification of statements. But while trying to implement an efficient modular exponential function I noticed that the current PlutusTx.Prelude does not even provide a simple power function (^). Digging even deeper I saw that the PlutusTx.Prelude only povides an even function and not even an odd function. How can I contribute to add these function to PlutusTx.Prelude?

Is my implementation correct? I import Plutus.Prelude as Prel. Do I also need to add the template haskell inlinable pragma if I make this a library?

power :: Integer -> Integer -> Integer
power x n |(n==1) = x
        | Prel.even n       = (power x ( Prel.divide n 2))*(pow x ( Prel.divide n 2)) 
        | Prel.even (n-1)   = x * (power x (n-1))

expMod :: Integer -> Integer -> Integer -> Integer
expMod b e m
    | b == 1    = b
    | e == 0    = 1
    | e == 1    = b `Prel.modulo` m
    | even e    = let p = expMod b (e `Prel.divide` 2) m `Prel.modulo` m
                   in (power p (2::Integer)) `Prel.modulo` m
    | otherwise = (b * expMod b (e-1) m) `Prel.modulo` m

which seems to compile without the pragma in a validator.


1 Answer 1


Try this function:

power x n
    | n == 0  =  1
    | x == 0  =  0
    | even n = ( power x (n 'div' 2) ) * ( power x (n 'div' 2) )
    | otherwise n = x * ( power x ((n - 1) 'div' 2)) * ( power x ((n - 1) 'div' 2) )

Look at the type signature for even: even :: (Integral a) => a -> Bool. odd has a similar signature.

So you can see that even and odd take any type of the Integral typeclass and evaluate it. Then look at the signature for /: (/) :: (Fractional a) => a -> a -> a.

/ takes only Fractional types, not Integral ones. It's impossible for one type to be evaluated by both those functions. In this case, there's an easy fix: use div instead of /.

Note that if you use div as an infix function (place it between the arguments) you'll need to put backticks around div.

  • 1
    Thank you for correcting my bad cases, but note that the use of odd here is not allowed since PlutusTx.Prelude does not have this.
    – Fermat
    Mar 22, 2022 at 20:58
  • Well in this case should otherwise (instead of odd) also work, but an odd would be also great. 👍 Mar 22, 2022 at 21:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.