作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在研究操作系统的类型级列表,我编写了两个类型级函数,一个用于组合两个列表,另一个用于获取它们的交集。我无法让交集功能正常工作。
(gc 7.10.3)
这是组合函数,按预期工作:
*Main> (combineSupportedOS debian freeBSD) :: OSList '[OSDebian, OSFreeBSD]
OSList [OSDebian,OSFreeBSD]
*Main> (intersectSupportedOS debian debian) :: OSList '[OSDebian]
Couldn't match expected type ‘IntersectOSList ['OSDebian] '['OSDebian]’
with actual type ‘'['OSDebian]’
{-# LANGUAGE TypeOperators, PolyKinds, DataKinds, TypeFamilies, UndecidableInstances #-}
import Data.Typeable
import Data.String
import Data.Type.Bool
import Data.Type.Equality
data SupportedOS = OSDebian | OSFreeBSD
deriving (Show, Eq)
data OSList (os :: [SupportedOS]) = OSList [SupportedOS]
deriving (Show, Eq)
debian :: OSList '[OSDebian]
debian = typeOS OSDebian
freeBSD :: OSList '[OSFreeBSD]
freeBSD = typeOS OSFreeBSD
typeOS :: SupportedOS -> OSList os
typeOS o = OSList [o]
combineSupportedOS
:: (r ~ ConcatOSList l1 l2)
=> OSList l1
-> OSList l2
-> OSList r
combineSupportedOS (OSList l1) (OSList l2) = OSList (l1 ++ l2)
type family ConcatOSList (list1 :: [a]) (list2 :: [a]) :: [a]
type instance ConcatOSList '[] list2 = list2
type instance ConcatOSList (a ': rest) list2 = a ': ConcatOSList rest list2
intersectSupportedOS
:: (r ~ IntersectOSList l1 l2)
=> OSList l1
-> OSList l2
-> OSList r
intersectSupportedOS (OSList l1) (OSList l2) = OSList (filter (`elem` l2) l1)
type family IntersectOSList (list1 :: [a]) (list2 :: [a]) :: [a]
type instance IntersectOSList '[] list2 = list2
type instance IntersectOSList (a ': rest) list2 =
If (ElemOSList a list2)
(a ': IntersectOSList rest list2)
(IntersectOSList rest list2)
type family ElemOSList a (list :: [b]) :: Bool
type instance ElemOSList a '[] = False
type instance ElemOSList a (b ': bs) =
If (a == b)
True
(ElemOSList a bs)
type family EqOS (a :: SupportedOS) (b :: SupportedOS) where
EqOS a a = True
EqOS a b = False
type instance a == b = EqOS a b
最佳答案
主要修复如下:
- type family ElemOSList a (list :: [b]) :: Bool
+ type family ElemOSList (a :: SupportedOS) (list :: [SupportedOS]) :: Bool
type family IntersectOSList (list1 :: [a]) (list2 :: [a]) :: [a]
type instance IntersectOSList '[] list2 = '[]
type instance IntersectOSList (a ': rest) list2 =
If (ElemOSList a list2)
(a ': IntersectOSList rest list2)
(IntersectOSList rest list2)
type family ElemOSList (a :: SupportedOS) (list :: [SupportedOS]) :: Bool
type instance ElemOSList a '[] = False
type instance ElemOSList a (b ': bs) = a == b || ElemOSList a bs
关于haskell - 如何为类型级列表编写交集函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35878018/
我是一名优秀的程序员,十分优秀!