[Haskell-beginners] numerical types, the $ operator

Brent Yorgey byorgey at seas.upenn.edu
Sat Mar 28 17:34:20 EDT 2009

On Sat, Mar 28, 2009 at 11:18:46PM +0200, TG wrote:
> Hi all
> I'm trying to understand the following simple function
> >-- | fractional part of number.
> >frac :: (RealFrac a) => a -> a
> >frac x = x - fromInteger . floor $ x
> which apparently is wrong. Whereas this is ok
> >frac x = x - fromInteger (floor x)
> Is the 1st one wrong because it is trying to apply the _whole_ 'left of
> $' to the 'x' on the right?

Exactly. ($) has very low precedence, even lower than (-).

> How would an experienced guy write this without parentheses?

I'm fairly certain it's impossible to write it without using
parentheses.  I would probably just write

  x - fromInteger (floor x)

> Moreover, I've put the 'RealFrac' by looking at ":t floor".
> What kind of class constraint whould you put for doing eg:
> >frac x = x - fromInteger (floor (sqrt x) )
> since 'floor' takes fractional and 'sqrt' takes RealFrac? Some kind of
> super-class?

Every instance of RealFrac must also be an instance of Fractional, so
just putting RealFrac would be fine.  (And I didn't have this
memorized, I just started up ghci and typed ':info Fractional' and
':info RealFrac' to see how they are declared.)

> Seems that types are half the language, if not more ..

I think you're on to something there.  One of the great strengths of
Haskell is its strong, expressive static type system.  Type classes
are an especially nifty feature.  Unfortunately, the numeric class
hierarchy leaves a bit to be desired at times, so I hope you won't
draw too many general conclusions from frustrations with numeric
stuff. =)


More information about the Beginners mailing list