Necrobious'

Thursday, March 19, 2009

CS Puzzles

If your in to testing your computer science fu, checkout Project Euler. I'm only 10 problems in, but its a ton of fun.

A fun example of Haskell's newtype

Haskell's newtype keyword allows you to hide an existing type behind a new type definition. in working with them I though of a neat example that would help illustrate how they work:

{-# LANGUAGE GeneralizedNewtypeDeriving #-}

newtype Fahrenheit = Fahrenheit Float
deriving (Eq, Ord, Show, Num, Fractional)

newtype Celsius = Celsius Float
deriving (Eq, Ord, Show, Num, Fractional)

far2cel :: Fahrenheit -> Celsius
far2cel (Fahrenheit far) = Celsius $ (5 / 9) * (far - 32)

cel2far :: Celsius -> Fahrenheit
cel2far (Celsius cel) = Fahrenheit $ (cel * (9 / 5)) + 32

We're declaring two "new types" one named Fahrenheit and the other named Celsius, both are really just Floats. Then we declare two conversion functions, far2cel and cel2far, to handle marshaling a Fahrenheit temperature to a Celsius. We are using the *, -, and + operators from the Num class and the / operator from Fractional, by declaring our Fahrenheit and Celsius newtypes to derive from Fractional and from Num in conjunction with the -XGeneralizedNewtypeDeriving GHC option. Neat