Hi all,
 
I am currently write a program to type a dynamic string consist of 'A' or 'B'
 
for short, it works in this manner:
for 'A', it returns A :: A
for 'B', it returns B :: B
for "A", it returns Cons A Nil :: Cons A Nil
for "AB", it returns Cons A (Cons B Nil) :: Cons A (Cons B Nil)
...
 
The problem is I have to specifically annotate the output type, which is unaffordable, because I might have arbitrary-long string,
and I have infinitely many possible singleton types.
It seems it is impossible to do it in a type-safe way. Anyone of you have any idea to walk around that?
 
 
 
Regards,
Kenny
 
 
 
module Test where
 
data Content = C1 Char
      | C2 String deriving Eq
 
 
 
class MyType a where
    parse :: Content -> (Maybe a)
 
data A = A deriving (Show,Eq)
 
instance MyType A where
    parse (C1 'A') = Just A
    parse _ = Nothing
 
data B = B deriving (Show,Eq)
 
instance MyType B where
    parse (C1 'B') = Just B
    parse _ = Nothing
 

data Cons x xs = Cons x xs deriving Show
 
instance (MyType x,MyType xs) => MyType (Cons x xs) where
    parse (C2 (x:xs)) =  let maybehd = parse (C1 x) in
        case maybehd of
        Just hd ->
     let maybetl = parse (C2 xs) in
         case maybetl of
         Just tl ->
      Just ((Cons hd) tl)
         Nothing -> Nothing
        Nothing -> Nothing
    parse _ = Nothing
 

data Nil = Nil deriving (Show,Eq)
 
instance MyType Nil where
    parse (C2 [])  = Just Nil
    parse _ = Nothing
 
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Hugs session for:
/usr/share/hugs/lib/Prelude.hs
Test.hs
Type :? for help
Test> parse (C2 "A") :: Maybe (Cons A Nil)
Just (Cons A Nil)