[Haskell-beginners] The numeric type stack

Mike Meyer mwm at mired.org
Thu Dec 29 06:33:23 CET 2011


On Wed, 28 Dec 2011 22:23:12 -0600
Antoine Latter <aslatter at gmail.com> wrote:
> On Wed, Dec 28, 2011 at 8:54 PM, Mike Meyer <mwm at mired.org> wrote:
> > While haskell's type system is usually a delight to work with.
> > However, every once and a while I need to do mixed mode programming in
> > spite of Kernighan and Plauger's advice, and wind up cursing the
> > numeric type stack. I was wondering it there was a writeup on it
> > somewhere? Preferably one aimed at practical programming. A chapter in
> > Real World Haskell would have been ideal, but it doesn't seem to
> > exist.
> For shear comprehensiveness, there's always the language report:
> http://www.haskell.org/onlinereport/haskell2010/haskellch6.html#x13-1350006.4

Not to bad. Then again, I'm a long-time language lawyer, so others may
disagree.

> I don't know of anything that lays out and introduction with best
> practices and common pitfalls.

Given reading the report, and a little experimentation, I figured out
the problem I was having. I probably will in the future as well.

I wanted a percentage value rounded to the nearest integer. No
problem, it's just:

(%) a b = round $ 100 * a / b

And that works in ghci. However, it has the type

(%) :: (RealFrac a, Integral b) => a -> a -> b

Which means that the argument from length was of the wrong type for
this. And naturally, declaring the argument types that matched the
result from length caused type problems inside (%).

So, is there a reasonable way to get the value of two Integral types
divided by each other and rounded? How about one integral type and one
RealFrac? I know I can get it truncated towards either 0 or negative
infinity, but that's not what I want here.

	Thanks,
	<mike
-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/
Independent Software developer/SCM consultant, email for more information.

O< ascii ribbon campaign - stop html mail - www.asciiribbon.org



More information about the Beginners mailing list