A way to write fromRational
closer to your initial Ansatz is
fromRational r = let x = case invertMod (denominator r) (modulus x) of
Just inv -> normalize $ (numerator r) * inv
Nothing -> error "..."
in x
Since the result is of type Modular a
, we can obtain the modulus from it (without inspecting it). So all we need is to name it, so that we can refer to it where it's needed.