我有这段代码:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeFamilyDependencies #-}
{-# LANGUAGE DefaultSignatures #-}
module Study where
class C a where
type T a = r | r -> a
pred :: T a -> Bool
default pred :: T a ~ [a] => T a -> Bool
pred = not . null
instance C Integer where
type T Integer = [Integer]
它的工作原理如下:
λ Study.pred [1,2,3]
True
λ Study.pred ([ ] :: [Integer])
False
我想将简单的实例定义简化为:
instance C Integer
- 除非我特别希望与模式不同。
我计划拥有的大多数实例应该是默认的,T a ~ [a]
,但有些确实需要它们
拥有T
类型。我不愿意容忍许多相同的琐碎定义,如给定的
一。可以做些什么?
答案 0 :(得分:6)
您只需添加默认类型实例化:
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeFamilyDependencies #-}
{-# LANGUAGE DefaultSignatures #-}
module Study where
data One a = One a
class C a where
type T a = r | r -> a
-- This looks a bit strange,
-- because it looks like T is defined twice
-- but that's not actually the case
type T a = [a]
pred :: T a -> Bool
default pred :: T a ~ [a] => T a -> Bool
pred = not . null
instance C Integer
instance C Char where
type T Char = One Char
pred = const True
*Study> :t undefined :: T Integer
undefined :: T Integer :: [Integer]
*Study> :t undefined :: T Char
undefined :: T Char :: One Char