고려 :이 같은 미친 물건 작동하는지 아주 오싹하지만Typeclass 인스턴스의 2 차 폭발을 피하는 방법은 무엇입니까?
{-# OPTIONS -fglasgow-exts #-}
data Second = Second
data Minute = Minute
data Hour = Hour
-- Look Ma', a phantom type!
data Time a = Time Int
instance Show (Time Second) where
show (Time t) = show t ++ "sec"
instance Show (Time Minute) where
show (Time t) = show t ++ "min"
instance Show (Time Hour) where
show (Time t) = show t ++ "hrs"
sec :: Int -> Time Second
sec t = Time t
minute :: Int -> Time Minute
minute t = Time t
hour :: Int -> Time Hour
hour t = Time t
class TimeAdder a b c | a b -> c where
add :: Time a -> Time b -> Time c
instance TimeAdder Second Second Second where
add (Time s1) (Time s2) = sec (s1 + s2)
instance TimeAdder Second Minute Second where
add (Time s) (Time m) = sec (s + 60*m)
instance TimeAdder Second Hour Second where
add (Time s) (Time h) = sec (s + 3600*h)
instance TimeAdder Minute Second Second where
add (Time m) (Time s) = sec (60*m + s)
instance TimeAdder Minute Minute Minute where
add (Time m1) (Time m2) = minute (m1 + m2)
instance TimeAdder Minute Hour Minute where
add (Time m) (Time h) = minute (m + 60*h)
instance TimeAdder Hour Second Second where
add (Time h) (Time s) = sec (3600*h + s)
instance TimeAdder Hour Minute Minute where
add (Time h) (Time m) = minute (60*h + m)
instance TimeAdder Hour Hour Hour where
add (Time h1) (Time h2) = hour (h1 + h2)
add (minute 5) (hour 2)
--125min
, 나는 TimeAdder
인스턴스의 차 폭발을 피할 수있는 방법 궁금합니다.
시간, 분 및 초가 실제로 이런 종류의 유형 안전을 제공하는 후보가 아닙니다. 초 단위의 시간 만 허용합니까? 이런 종류의 유형 안전을위한 더 좋은 운동은 예를 들어 물리적 단위 일 수 있습니다. 여러분은'Time','Mass','Length' 등을 유령 타입으로하고 속도, 에너지 등에 대한 타입 안전 계산을 할 수 있습니다. 이것은 모든 타입이 너의 시간 예. – shang
@shang : 정확합니다. 나는 이것이 타입 클래스와 팬텀 타입에 대한 더 나은 핸들을 얻기위한 장난감의 예일 뿐이라고 언급 했어야 만한다. hammar의 첫 번째 대답은 시간 단위가있는 실제 응용 프로그램의 경우 훨씬 더 실용적입니다. – Landei