gpt4 book ai didi

haskell - 如何在这里避免显式类型签名?

转载 作者:行者123 更新时间:2023-12-04 13:20:14 24 4
gpt4 key购买 nike

class Listy a b where
fromList :: [b] -> a
toList :: a -> [b]
lifted :: ([b] -> [b]) -> (a -> a)
lifted f = fromList . f . toList

data MyString = MyString { getString :: String } deriving Show

instance Listy MyString Char where
toList = getString
fromList = MyString

现在我需要写例如 lifted (reverse::(String -> String)) (MyString "Foobar") .是否有避免需要类型签名的技巧?

最佳答案

本质上问题在于设置 a 的类型不会告诉编译器 b 的类型是什么是。您可能会认为,由于该类只有一个实例(其中 aMyStringbChar ),但是任何人都可以随时添加新实例。所以现在只有一个实例这一事实并不能帮助编译器决定你想要什么类型。

对此的解决方案是使用功能依赖项或类型族。后者是较新的解决方案,旨在最终“取代”前者,但目前两者仍然得到完全支持。 FD是否会消失还有待观察。无论如何,对于 FD:

class Listy a b | a -> b where ...

本质上,这表示“每个 a 只能有一个类实例”。换句话说,一旦你知道 a ,您可以随时确定 b . (但不是相反。)类的其他人看起来和以前一样。

替代方案是 TF:
class Listy a where
type Element a :: *
...

instance Listy MyString where
type Element MyString = Char
...

现在不是称为 b 的第二种类型,它被称为 Element a .字 Element就像一个类方法,它接受一个列表类型并返回相应的元素类型。然后你可以做
instance Listy ByteString where
type Element ByteString = Word8
...

instance Listy [x] where
type Element [x] = x
...

instance Ord x => Listy (Set x) where
type Element (Set x) = x
...

等等。 (并不是说 Listy 对上述所有类型都有意义;这些只是如何定义类的示例。)

关于haskell - 如何在这里避免显式类型签名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12929124/

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