ZVON > References > Haskell reference
| Indexes | Syntax | Prelude | Ratio | Complex | Numeric | Ix | Array | List | Maybe | Char | Monad | >> IO << | Directory | System | Time | Locale | CPUTime | Random

Module: IO
Function: bracket
Type: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
Description:

captures a common allocate, compute, deallocate idiom in which the deallocation step must occur even in the case of an error during computation. This is similar to try-catch-finally in Java.

The function evaluates the first argument and passes its value to both the second and the third argument. The third argument is evaluated next, and even if the evaluation of this argument causes an error, the second argument is evaluated in the last step.

Related:

Example 1
Program source: 

import IO

main = bracket (openFile "/tmp/foo.txt" ReadMode) (print)
               (\x -> return())

Output: {loc=/tmp/foo.txt,type=readable,binary=False,buffering=block (8192)}

Example 2
File: /tmp/foo.txt : 

HELLO
Program source: 

import IO

main = bracket (openFile "/tmp/foo.txt" ReadMode) (hClose)
               (\hdl ->
		  do x <- hGetChar hdl
		     y <- hGetChar hdl
                     print (x,y)
	       )


Output: ('H','E')