Undefined

From HaskellWiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

This is a very useful value: undefined :: a You can put it anywhere and it will compile. When evaluated, it throws an exception "undefined". But thanks to laziness you can put it anywhere you've not written yet:

   Haskell> let (x,y) = (undefined,"hello!") in y
   "hello!"

If you just want to get a function to compile, but you've not finished writing half of it, just stick an undefined in there. For example, say I'm writing a function to read from a file, print it out and parse it with a given parser; I haven't thought of the parse bit yet, but I want to check the rest of the function's okay, so I just stick an undefined in there:

   readFromFile :: Parser a -> SourceName -> IO (Either ParseError a)
   readFromFile parser path = do
     contents <- readFile path
     putStrLn $ contents
     return undefined

Now I come back to it, see the undefined and I know what needs to be written:

   readFromFile :: Parser a -> SourceName -> IO (Either ParseError a)
   readFromFile parser path = do
     contents <- readFile path
     putStrLn $ contents
     return $ parse parser path contents

It's also good for initialising record values:

   MyRecord { rec_name = "Foo", rec_other = undefined }

This function is the same: error :: String -> a You can use it in the same way:

   MyRecord { rec_name = "Foo", rec_other = error "rec_other is empty" }
   readFromFile :: Parser a -> SourceName -> IO (Either ParseError a)
   readFromFile parser path = do
     contents <- readFile path
     putStrLn $ contents
     return $ error "implement the return part of readfromfile"
   Haskell> (2*2,error "failure!")
   (4,*** Exception: failure!