gpt4 book ai didi

haskell - 封闭类型族和奇怪的函数类型

转载 作者:行者123 更新时间:2023-12-04 06:18:30 25 4
gpt4 key购买 nike

抱歉,我想不出更好的问题标题,所以请继续阅读。想象一下,我们有一个封闭的类型族,它将每个类型映射到它对应的 Maybe除了也许自己:

type family Family x where
Family (Maybe x) = Maybe x
Family x = Maybe x

我们甚至可以使用该类型族声明一个函数:
doMagic :: a -> Family a
doMagic = undefined

exampleA = doMagic $ Just ()
exampleB = doMagic $ ()

在 GHCi 中使用它表明可以评估此​​函数应用程序的类型:
*Strange> :t exampleA      
exampleA :: Maybe ()
*Strange> :t exampleB
exampleB :: Maybe ()

问题是是否可以提供 doMagic 的任何实现。 undefined 除外的功能?例如,假设我想将每个值包装成 Just构造函数,除了应该保持不变的Maybes,我该怎么做?我尝试使用类型类,但如果不使用封闭类型系列,则无法为 doMagic 函数编写可编译签名,有人可以帮我吗?

最佳答案

您可以使用另一个封闭类型族来区分Maybe x来自 x然后您可以使用另一个类型类来提供 doMagic 的单独实现对于这两种情况。快速而肮脏的版本:

{-# LANGUAGE TypeFamilies, MultiParamTypeClasses,
FlexibleInstances, UndecidableInstances, ScopedTypeVariables #-}

type family Family x where
Family (Maybe x) = Maybe x
Family x = Maybe x

data True
data False

type family IsMaybe x where
IsMaybe (Maybe x) = True
IsMaybe x = False


class DoMagic a where
doMagic :: a -> Family a

instance (DoMagic' (IsMaybe a) a (Family a)) => DoMagic a where
doMagic = doMagic' (undefined :: IsMaybe a)


class DoMagic' i a r where
doMagic' :: i -> a -> r

instance DoMagic' True (Maybe a) (Maybe a) where
doMagic' _ = id

instance DoMagic' False a (Maybe a) where
doMagic' _ = Just


exampleA = doMagic $ Just ()
exampleB = doMagic $ ()

关于haskell - 封闭类型族和奇怪的函数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26641559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com