Created
November 19, 2012 14:05
-
-
Save blerou/4110825 to your computer and use it in GitHub Desktop.
Let's play Haskell! - #5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- array($year, $model, $price) | |
-- (Int, String, Int) | |
type Price = Int | |
data CarType = Ford | Chevrolet deriving (Show) | |
data Vehicle = Car Int CarType Price | |
| Bicycle Price | |
| Motor Price deriving (Show) | |
data Accessory = SteeringWheel Price | Brake Price deriving (Show) | |
type Store = [Vehicle] | |
class Priceable a where | |
price :: a -> Price | |
instance Priceable Vehicle where | |
price (Car _ _ p) = p | |
price (Bicycle p) = p | |
instance Priceable Accessory where | |
price (SteeringWheel p) = p | |
price (Brake p) = p | |
storePrice :: (Priceable a) => [a] -> Price | |
storePrice [] = 0 | |
storePrice (p:ps) = price p + storePrice ps | |
storePrice2 ps = tailStorePrice ps 0 | |
tailStorePrice :: (Priceable a) => [a] -> Price -> Price | |
tailStorePrice [] pr = pr | |
tailStorePrice (p:ps) pr = tailStorePrice ps (pr + price p) | |
storePrice3 ps = foldl (\sum p -> sum + price p) 0 ps | |
storePrice4 :: (Priceable a) => [a] -> Price | |
storePrice4 = sum . map price | |
sampleStore :: Store | |
sampleStore = [mustang65, corvette63, mustang66, csepel] | |
sampleAccessories :: [Accessory] | |
sampleAccessories = [SteeringWheel 12, Brake 23] | |
mustang65 :: Vehicle | |
mustang65 = Car 1965 Ford 1111 | |
mustang66 :: Vehicle | |
mustang66 = Car 1966 Ford 1234 | |
corvette63 :: Vehicle | |
corvette63 = Car 1963 Chevrolet 2222 | |
csepel :: Vehicle | |
csepel = Bicycle 12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment