我想弄清楚Bool -> Maybe ()
是否同构。
可能的组合是:
True -> Just ()
True -> Nothing
False -> Just ()
False -> Nothing
我想说,它是同构的,对于每种组合,它都有单独的函数对其求逆。
如何证明上述同构是同构的?
答案 0 :(得分:7)
Bool
和Maybe ()
是同构类型(ignoring problems involving bottom),从两者之间的以下映射可以看出:
b2m :: Bool -> Maybe ()
b2m True = Just ()
b2m False = Nothing
m2b :: Maybe () -> Bool
m2b (Just ()) = True
m2b Nothing = False
很容易验证b2m . m2b
和m2b . b2m
都等于id
:
m2b . b2m $ True == m2b (b2m True) == m2b (Just ()) == True == id True
m2b . b2m $ Fals == m2b (b2m False) == m2b Nothing == False == id False
b2m . m2b (Just ()) == b2m (m2b (Just ())) == b2m True == Just () == id (Just ())
b2m . m2b Nothing == b2m (m2b Nothing) == b2m False == Nothing == id Nothing
在您的问题中,您没有一个词素。您具有类型为Bool -> Maybe ()
的4个不同功能的构造块,如下所示:
f1,f2,f3,f4 :: Bool -> Maybe ()
f1 True = Just ()
f1 False = Nothing
f2 True = Nothing
f2 False = Just ()
f3 True = Just ()
f3 False = Just ()
f4 True = Nothing
f4 False = Nothing
同样,Maybe () -> Bool
类型有4种不同的功能:
f5,f6,f7,f8 :: Maybe () -> Bool
f5 (Just ()) = True
f5 Nothing = False
f6 (Just ()) = False
f6 Nothing = True
f7 (Just ()) = True
f7 Nothing = True
f8 (Just ()) = False
f8 Nothing = False
一些功能对形成同构,但有些则不。该答案的顶部显示f1
和f5
可以,但是f3
和f8
则不能。
f3 . f8 $ (Just ()) == f3 (f8 Just ()) == f3 False == Just () == id (Just ())
f3 . f8 $ Nothing == f3 (f8 Nothing) == f3 False == Just () != id Nothing
答案 1 :(得分:6)
在Haskell中,这些类型是“道德上的”同构,而不是精确的同构。
Bool
具有三个值:True
,False
和_|_
(底部,表示未终止或错误)。
Maybe ()
具有四个值:Nothing
,Just ()
,Just _|_
和_|_
。
我们倾向于根据定义对类型的值进行部分排序。在此部分顺序下,它们形成一个 Scott域,这是一个具有一定完整性属性的半格。在这种情况下,
_|_ < Just _|_ < Just ()
_|_ < Nothing
递归类型导致更有趣的域。例如,类型[Natural]
包括链条
_|_
< 1 : _|_
< 1 : 1 : _|_
< 1 : 1 : 2 : _|_
< ...
< fibs
答案 2 :(得分:4)
如果我们使用|T|
捐赠某种类型的可能值,则可以看到|()| = 1
(只有一种构建()
的方法)。此外,我们可以看到,对于data Maybe a = Just a | Nothing
,我们有|Maybe a| = 1 + |a|
,因此有|Maybe ()| = 1 + |()| = 1 + 1 = 2
。因此,|Maybe ()|
有两个不同的值。 data Bool = True | False
的相同练习向我们显示|Bool| = 1 + 1 = 2
,因此这两种类型的居民数量完全相同。
要显示这些类型是同构的,我们只需要构造一个同构。这是从一种类型到另一种类型的函数,因此还有一个反函数:
toBool :: Maybe () -> Bool
toBool Nothing = False
toBool (Just ()) = True
fromBool :: Bool -> Maybe ()
fromBool False = Nothing
fromBool True = Just ()
toBool . fromBool = id
和fromBool . toBool = id
。