我正在尝试在Haskell中编译泛型类/类型模式的简单示例(请参阅http://www.haskell.org/ghc/docs/latest/html/users_guide/generic-classes.html)但它不会编译.关于代码有什么问题的任何想法都会有所帮助.
根据该文件应该有一个模块Generics与数据类型Unit,:*:以及:+:约但GHC(6.12.1)投诉Not in scope: data constructor 'Unit'等.
好像有一个包即时泛型与数据类型:*:,:+:以及U但是当我输入(而不是该模块Generics),我得到的错误
Illegal type pattern in the generic bindings
{myPrint _ = ""}
Run Code Online (Sandbox Code Playgroud)
完整的源代码是
import Generics.Instant
class MyPrint a where
myPrint :: a -> String
myPrint {| U |} _ = ""
myPrint {| a :*: b |} (x :*: y) = "" (show x) ++ ":*:" ++ (show y)
myPrint {| a :+: b |} _ = ""
data Foo = Foo String
instance MyPrint a => MyPrint a
main = myPrint $ Foo "hi"
Run Code Online (Sandbox Code Playgroud)
我用它编译它
ghc --make Foo.hs -fglasgow-exts -XGenerics -XUndecidableInstances
Run Code Online (Sandbox Code Playgroud)
PS模块Generics导出没有数据类型,只有函数:
canDoGenerics
mkGenericRhs
mkTyConGenericBinds
validGenericInstanceType
validGenericMethodType
Run Code Online (Sandbox Code Playgroud)
好吧,我不太了解泛型,但是你要找的符号都在Data.Generics模块中,所以我做了
import Data.Generics
Run Code Online (Sandbox Code Playgroud)
第二,行
myPrint {| a :*: b |} (x :*: y) = "" (show x) ++ ":*:" ++ (show y)
Run Code Online (Sandbox Code Playgroud)
有两个问题:第一,""显然太多了.其次,你不能使用show因为使用的类型不一定是Show类型类的实例.所以我做了这一行
myPrint {| a :*: b |} (x :*: y) = (myPrint x) ++ ":*:" ++ (myPrint y)
Run Code Online (Sandbox Code Playgroud)
最后,用
instance MyPrint a => MyPrint a
Run Code Online (Sandbox Code Playgroud)
你首先要求它a是一个实例,MyPrint然后你要求编译器派生一个你需要已经存在的MyPrint实例a.这对我有用:
instance MyPrint Foo
Run Code Online (Sandbox Code Playgroud)
但是,您必须首先手动提供实例,String以便编译器具有派生的起点:
instance MyPrint String where
myPrint s = s
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.