
Hej hej! I was writing some code using Ratio, and even though I know it's tucked behind an abstraction barrier, I really wanted access to the Ratio data constructor ':%'. I wrote invertRatio like such: invertRatio r = denominator r % numerator But I really wanted to write it like this: invertRatio (n :% d) = d % n I understand that exposing ':%' causes problems, since it allows us not only to pick apart ratios, but to construct bad ones that would normally be caught when constructed with '%'. (Such as '1:%0'.) Is there any way to avoid this, while still letting the user benefit from the nice pattern matching syntax that exposing the data constructor allows? Kram, Casey Rodarmor

2008/9/29 Casey Rodarmor
invertRatio r = denominator r % numerator
Ratio is an instance of Fractional, which means : invertRation = recip ou invert f = 1 / f (probably the default definition of recip anyway).
Is there any way to avoid this, while still letting the user benefit from the nice pattern matching syntax that exposing the data constructor allows?
To this more general question : allow the convenience of pattern matching while keeping a datatype abstract, the latest GHC (6.10) bring a new extension called "view pattern", it may not be ideal but it should be pretty useful in this direction. http://hackage.haskell.org/trac/ghc/wiki/ViewPatterns -- Jedaï
participants (2)
-
Casey Rodarmor
-
Chaddaï Fouché