Hacker News new | past | comments | ask | show | jobs | submit login

There's also Haskell's "bracket" (https://wiki.haskell.org/Bracket_pattern) which is similar to python's "with" statement but with plain functions instead of context managers.



Thanks for the pointer! I'm having trouble categorizing this one, tbh. (also its relationship to what dwohnitmok says on this HN discussion)

Superficially, the code on this Wikipedia page looks like the bracket pattern in similar to the `dynamic-unwind` low-level function and friends in Scheme and Lisp - but then again I realize the notion of cleanup probably only makes sense when mutable state exists :)

How does that look in practice? Is there a clever way to use the bracket operator together with Haskell's syntactic sugar for monads?


An example use of bracket would be:

    do 
      filename <- getLine
      fileContents <- bracket (openFile filename) (closeFile) $ \file -> do
        contents <- readFile file
        if contents == ""
          then do 
            writeFile file "hello world" 
            return "hello world"
          else do
            return contents
      putStrLn fileContents
this ensures that the file is closed even if readFile or writeFile throw exceptions.




Join us for AI Startup School this June 16-17 in San Francisco!

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

Search: