[Haskell-cafe] Exception for NaN
daniel.is.fischer at googlemail.com
Sat May 14 11:11:12 CEST 2011
On Friday 13 May 2011 23:41:34, Casey McCann wrote:
> On Fri, May 13, 2011 at 4:48 PM, Luke Palmer <lrpalmer at gmail.com> wrote:
> > On Thu, May 12, 2011 at 5:50 PM, Daniel Fischer
> > <daniel.is.fischer at googlemail.com> wrote:
> >> Prelude Data.List> maximum [0,-1,0/0,-5,-6,-3,0/0,-2]
> >> 0.0
> >> Prelude Data.List> minimum [0,-1,0/0,-5,-6,-3,0/0,-2]
> >> -2.0
> >> Prelude Data.List> sort [0,-1,0/0,-5,-6,-3,0/0,-2]
> >> [-6.0,-5.0,-2.0,NaN,-3.0,NaN,-1.0,0.0]
> > Wow, that's the best example of NaN poison I've seen.
> Somewhat less impressive, but would everyone expect these functions to
> be equivalent up to performance characteristics?
> f :: (Eq a) => [a] -> [a]
> f = nub . concatMap (replicate 5)
> g :: (Eq a) => [a] -> [a]
> g = nub
> If the answer that springs to mind is "yes, for any well-behaved
> instance of Eq", well...
My answer is "Yes, for any well-behaved instance of Eq or for lists of
Float/Double not containing any NaN (and similar caveats for types using
these)" - other types with special cases may exist, none springs to mind.
It's (hopefully) well-known that the Eq and Ord instances of Double and
Float aren't well-behaved in the presence of NaNs, but you can't have
consistent instances which do what you expect on non-NaN values.
Not having Eq and Ord instances for Double and Float would be extremely
inconvenient (too inconvenient to seriously consider, I think), so one can
a) do what's done now
b) make NaNs an error
c) come up with a brilliant solution.
While c) has not been achieved, I consider a) the least evil option.
> Bonus question: Should this function ever return False?
> h :: (Ord a) => a -> a -> Bool
> h x y = case compare x y of
> GT -> x > y
> EQ -> x == y
> LT -> x < y
Not for well-behaved Ord instances, nor for Double and Float, provided
neither argument is NaN (and derived cases).
> - C.
More information about the Haskell-Cafe