DAY 19
0
Software Development

## mostly:functional 第十八章：不同事物的相同部份

-- 唐鳳, RubyConf 座談, 2014

-- 0610

-- 0630

-- 0709

「From first principle」

`class` ？又不是物件導向，這東西怎麼會出現在這裡？

# class is for the typeclass

## 自動推導

``````-- Haskell 語法
data Temp = Celsius Float | Fahrenheit Float
deriving (Show)

temp1 = Celsius 50.0
temp2 = Celsius 50.0
temp3 = Celsius 60.0

temp1 == temp2

-- => <interactive>:3:1: error:
--     • No instance for (Eq Temp) arising from a use of ‘==’
``````

``````-- Haskell 語法
data Temp = Celsius Float | Fahrenheit Float
deriving (Show, Eq)

temp1 = Celsius 50.0
temp2 = Celsius 50.0

temp1 == tmep2
-- => True
``````

``````-- Haskell 語法
data Temp = Celsius Float | Fahrenheit Float
deriving (Show, Eq, Ord)

temp1 = Celsius 50.0
temp3 = Celsius 60.0

temp1 > tmep3
-- => False
``````

## 自行實作

``````-- Haskell 語法
toF temp =
case temp of
Celsius t -> Fahrenheit (t * 9 / 5 + 32)
_ -> temp
``````

``````-- Haskell 語法
*Main> :i Eq
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
{-# MINIMAL (==) | (/=) #-}
-- Defined in ‘GHC.Classes’
``````

``````-- Haskell 語法
class Eq a => Ord a where
compare :: a -> a -> Ordering
(<) :: a -> a -> Bool
(<=) :: a -> a -> Bool
(>) :: a -> a -> Bool
(>=) :: a -> a -> Bool
max :: a -> a -> a
min :: a -> a -> a
{-# MINIMAL compare | (<=) #-}
-- Defined in ‘GHC.Classes’
``````

``````-- Haskell 語法
data Temp = Celsius Float | Fahrenheit Float
deriving (Show)

toF temp =
case temp of
Celsius t -> Fahrenheit (t * 9 / 5 + 32)
_ -> temp

instance Eq Temp where
Fahrenheit t1 == Fahrenheit t2 = t1 == t2
t1 == t2 = (toF t1) == (toF t2)

instance Ord Temp where
Fahrenheit t1 <= Fahrenheit t2 = t1 <= t2
t1 <= t2 = (toF t1) <= (toF t2)

---- 用看看
temp1 = Celsius 50
temp2 = Fahrenheit 122
temp3 = Fahrenheit 100

temp1 == temp2 -- => True
temp1 < temp3 -- => False
``````

<應該還要有故事但如你所見我的哏基本上用完了還在生>

[to be continue]