Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell 这里如何避免显式类型签名?_Haskell_Typeclass - Fatal编程技术网

Haskell 这里如何避免显式类型签名?

Haskell 这里如何避免显式类型签名?,haskell,typeclass,Haskell,Typeclass,现在我需要编写例如lifted(反向::(String->String))(MyString“Foobar”)。有什么技巧可以避免需要类型签名吗?您可以试试-XFunctionalDependencies class Listy a b where fromList :: [b] -> a toList :: a -> [b] lifted :: ([b] -> [b]) -> (a -> a) lifted f = fromList .

现在我需要编写例如
lifted(反向::(String->String))(MyString“Foobar”)
。有什么技巧可以避免需要类型签名吗?

您可以试试-XFunctionalDependencies

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

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

解决方案是使用函数依赖项或类型族。后者是较新的解决方案,旨在最终“取代”前者,但目前这两种解决方案仍得到充分支持。FDs是否会消失还有待观察。无论如何,对于FDs:

class Listy a b | a -> b where
   fromList :: [b] -> a
   toList :: a -> [b]
   lifted :: ([b] -> [b]) -> (a -> a) 
   lifted f = fromList . f . toList
本质上,这表示“每个
a
只能有一个类实例”。换句话说,一旦知道
a
,就可以随时确定
b
。(但不是相反)班上的其他同学看起来和以前一样

另一种选择是TFs:

class Listy a b | a -> b where ...
现在,第二种类型被称为
b
,而不是
元素a
。单词
元素
的作用类似于类方法,它采用列表类型并返回相应的元素类型。然后你就可以做了

class Listy a where
  type Element a :: *
  ...

instance Listy MyString where
  type Element MyString = Char
  ...
等等。(并不是说Listy对上述所有类型都有意义;这些只是如何定义类的示例。)

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
  ...