Ign*_*rov 1 haskell types type-families
我有这个代码:
{-# 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]
Run Code Online (Sandbox Code Playgroud)
它的工作原理如下:
? Study.pred [1,2,3]
True
? Study.pred ([ ] :: [Integer])
False
Run Code Online (Sandbox Code Playgroud)
我想简化实例定义只是为了:
instance C Integer
Run Code Online (Sandbox Code Playgroud)
- 除非我特意要偏离模式.
我计划拥有的大多数实例应该是默认的T a ~ [a]
,但是有些确实需要自己的T
类型.我不愿意容忍许多相同的琐碎定义,如给定的.可以做些什么?
您只需添加默认类型实例化:
{-# 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
Run Code Online (Sandbox Code Playgroud)
*Study> :t undefined :: T Integer
undefined :: T Integer :: [Integer]
*Study> :t undefined :: T Char
undefined :: T Char :: One Char
Run Code Online (Sandbox Code Playgroud)