在haskell中自动转换类型 [英] Auto convert type in haskell
问题描述
我写了一些有用的函数来做逻辑运算。它看起来像(a和b或c)`belongs` x
。
I've written some helpful functions to do logical operation. It looks like (a and b or c) `belongs` x
.
感谢 Num
, IsList
和 OverloadedLists
,我可以将它用于整数和列表。 / p>
Thanks to Num
, IsList
and OverloadedLists
, I can have it for integers and lists.
λ> (1 && 2 || 3) `belongs` [2]
False
λ> (1 && 2 || 3) `belongs` [1, 2]
True
λ> (1 && 2 || 3) `belongs` [3]
True
λ> :set -XOverloadedLists
λ> ([1, 2] && [2, 3] || [3, 4]) `contains` 1
False
λ> ([1, 2] && [2, 3] || [3, 4]) `contains` 2
True
我这样做:
I do it this way:
newtype BoolLike a = BoolLike ((a -> Bool) -> Bool)
(&&) :: BoolLike a -> BoolLike a -> BoolLike a
BoolLike f && BoolLike g = BoolLike $ \k -> f k P.&& g k
infixr 3 &&
toBoolLike :: a -> BoolLike a
toBoolLike x = BoolLike $ \k -> k x
belongs :: Eq a => BoolLike a -> [a] -> Bool
belongs (BoolLike f) xs = f (\x -> x `elem` xs)
contains :: Eq a => BoolLike [a] -> a -> Bool
contains (BoolLike f) x = f (\xs -> x `elem` xs)
instance Num a => Num (BoolLike a) where
fromInteger = toBoolLike . fromInteger
我要做的是适用于任何类型,无需手动转换 a
到 BoolLike a
。
What I am going to do is make it suit for any types, without manually convert a
to BoolLike a
.
我该如何实现它?
第一次尝试:
First try:
class IsBool a where
type BoolItem a
toBool :: a -> BoolItem a
instance IsBool (BoolLike a) where
type BoolItem (BoolLike a) = BoolLike a
toBool = id
instance IsBool a where
type BoolItem a = BoolLike a
toBool = toBoolLike
失败:
Conflicting family instance declarations:
BoolItem (BoolLike a) -- Defined at BoolLike.hs:54:8
BoolItem a -- Defined at BoolLike.hs:58:8
推荐答案
你可以试试这个 b
You could try this
type family BoolItem a where
BoolItem (BoolLike a) = BoolLike a
BoolItem a = BoolLike a
class IsBool a where
toBool :: a -> BoolItem a
instance IsBool (BoolLike a) where
toBool = id
instance (BoolItem a ~ BoolLike a) => IsBool a where
toBool = toBoolLike
通过将类型族移出课程,您可以为所有类型定义它。然后剩下的就是限制其中一个实例。别忘了你还需要做一个 OVERLAPPABLE
By moving the type family out of the class you can define it for all types. Then all that remains is restricting one of the instances. Don't forget you'll also need to make that one OVERLAPPABLE
这篇关于在haskell中自动转换类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!