dynamic types
Hal Daume III
hdaume@ISI.EDU
Tue, 7 Jan 2003 12:19:32 -0800 (PST)
You are correct. You can't say:
let x = if ??? then () else (5::Integer)
because then the compiler can't assign a type to x.
However, to achieve what you want, you might try something like this
(untested code follows):
> main = do
> l <- getLine
> let x = case maybeRead l of
> Just () -> Left ()
> _ -> case maybeRead l of
> Just (i::Integer) -> Right i
> if isLeft x
> then putStrLn "Unit type detected"
> else putStrLn "Integer type detected"
where
> maybeRead :: Read a => String -> Maybe a
> maybeRead x = case readsPrec x of
> [(a,_)] -> Just a
> _ -> Nothing
or something like that.
Another way to do it would be to define a "universal" type:
> data Univ = UUnit () | UInteger Integer | UDouble Double | ...
and define an instance of read on it that loos like the cascaded cases
from above...
HTH,
Hal
--
Hal Daume III
"Computer science is no more about computers | hdaume@isi.edu
than astronomy is about telescopes." -Dijkstra | www.isi.edu/~hdaume
On Tue, 7 Jan 2003, Richard Uhtenwoldt wrote:
> Just want to make sure I understand.
>
> There does not exist a Haskell implementation-specific extension which
> provides the sort of dynamic type that would allow one to discriminate
> at run time between built-in types; right? eg,
>
> main=do
> object<-readLn
> case object of --or some such syntax
> ()->putStrLn "void type detected"
> (a::Integer)->putStrLn "Integer type detected"
>
> For those readers whose prelude is rusty, I quote from the prelude:
>
> readLn :: Read a => IO a
> readLn = do l <- getLine
> r <- readIO l
> return r
>
>
> And even if the object being discriminated "lacks
> polymorphicity", eg, this next, that does not change the answer
> to my question; right?
>
> main=do
> command<-readLn
> let
> object=case command of
> "Integer"->(5::Integer)
> "Void"->()
> case object of
> ()->putStrLn "void type detected"
> (a::Integer)->putStrLn "Integer type detected"
> _______________________________________________
> Haskell mailing list
> Haskell@haskell.org
> http://www.haskell.org/mailman/listinfo/haskell
>