Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

In Haskell, there's the "bracket" function with generalizes the "with" concept.

  withFile fileName mode = bracket (openFile fileName mode) hClose
Then:

  withFile "/usr/share/dict/words" ReadMode $ \h -> do
    contents <- hGetContents h
    count (lines contents)
No need for macros for this. Just passing anonymous code blocks easily.

Interestingly, the type of withFile, after its given the filename and filemode args is:

  (Handle -> IO a) -> IO a
Which is the type of a CPS'd computation. CPS'd computations are called the Cont monad in Haskell, which is defined as:

  data Cont r a = Cont ((a -> r) -> r)
So the above type of withFile can be written as:

  Cont (IO a) Handle
And if we have, for example, multiple resources we're bracketing over, we can represent them as multiple Cont values. Then we can monadically compose them, which is equivalent to Python's "nested" function (Except we also have type safety).


My comment intended to show how macros can allow one to create syntactic abstraction. That one can accomplish X without creating new syntactic abstraction, or that some language already has syntactic abstraction for X, is wholly irrelevant.


Well, I'm always looking for problems that are uniquely well solved by macros.

Lisps pay a dear price to have macros. If their capabilities are covered otherwise (in ways that are not as costly), why have them?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: