pattern matching accross instance declarations
Doing read/show on existential types would be a lot easier if pattern matching worked *accross* instance declarations and not only within them For example, this code produces an "Ambiguous type variable" GHC error, but it would be really helpful if it didn't: data MyExistantialType=forall v.(Show v)=>EType v class MyExistentialTypeable a where toMyType::String->MyExistantialType instance MyExistentialTypeable String where toMyType "String" = EType "foo" instance MyExistentialTypeable Int where toMyType "Int" = EType "bar" tVal (EType v)=show v main = print $ tVal $ toMyType "String" I know Haskell has a general prohibition on defining functions in multiple locations, but instance declarations already violate it. Why not go all the way? My current approach is manually writing lookup functions in addition to per-instance functions and that is both annoying and error-prone. -Alex- ______________________________________________________________ S. Alexander Jacobson tel:917-770-6565 http://alexjacobson.com
S. Alexander Jacobson wrote:
data MyExistantialType=forall v.(Show v)=>EType v
class MyExistentialTypeable a where toMyType::String->MyExistantialType
instance MyExistentialTypeable String where toMyType "String" = EType "foo"
instance MyExistentialTypeable Int where toMyType "Int" = EType "bar"
tVal (EType v)=show v main = print $ tVal $ toMyType "String"
The type class isn't necessary here, since toMyType has the same type in every instance anyway (namely String->MyExistentialType). You can simply write data MyExistantialType=forall v.(Show v)=>EType v toMyType "String" = EType "foo" toMyType "Int" = EType "bar" tVal (EType v)=show v main = print $ tVal $ toMyType "String" -- Ben
My point is that I want to be able to add new toMyType definitions without having to modify some central library file and I want the compiler to warn me when I haven't defined one for each instance. -Alex- On Thu, 2 Dec 2004, Ben Rudiak-Gould wrote:
S. Alexander Jacobson wrote:
data MyExistantialType=forall v.(Show v)=>EType v
class MyExistentialTypeable a where toMyType::String->MyExistantialType
instance MyExistentialTypeable String where toMyType "String" = EType "foo"
instance MyExistentialTypeable Int where toMyType "Int" = EType "bar"
tVal (EType v)=show v main = print $ tVal $ toMyType "String"
The type class isn't necessary here, since toMyType has the same type in every instance anyway (namely String->MyExistentialType). You can simply write
data MyExistantialType=forall v.(Show v)=>EType v
toMyType "String" = EType "foo" toMyType "Int" = EType "bar"
tVal (EType v)=show v main = print $ tVal $ toMyType "String"
-- Ben
______________________________________________________________ S. Alexander Jacobson tel:917-770-6565 http://alexjacobson.com
participants (2)
-
Ben Rudiak-Gould -
S. Alexander Jacobson