Difference between revisions of "User:Zzo38/Proposal for macros"

From HaskellWiki
Jump to navigation Jump to search
(New page: This document list proposal for use of macros in Haskell. =Defining macros= =Macros for catching pattern failure= Example: a :: Int -> Int -> Int; a 0 x = x; a 1 x = x + x; b :: Int...)
 
Line 6: Line 6:
   
 
Example:
 
Example:
  +
{-# LANGUAGE Macro #-}
  +
import Control.Exception.Macro;
 
a :: Int -> Int -> Int;
 
a :: Int -> Int -> Int;
 
a 0 x = x;
 
a 0 x = x;
Line 35: Line 37:
 
d 0 = return id;
 
d 0 = return id;
 
f = fail "undefined";
 
f = fail "undefined";
  +
  +
Note that <tt>_Catch</tt> and so on are macros, not functions. A macro is not a first-class value in the program, and cannot be used at run-time, but can have operations that a function doesn't have.
  +
  +
When calling the new function created by the macro, errors are converted to the return value instead (a function could not read undefined values, but a macro could change it into a different function so that it is not undefined).
  +
  +
You could specify strictifying with do-notation to ensure everything in there is defined before returning a value, so that an undefined value will be caught ahead of time.
  +
  +
User errors and pattern match errors can be caught even in a pure code, but out of memory error can only be caught in I/O actions.

Revision as of 20:01, 12 January 2012

This document list proposal for use of macros in Haskell.

Defining macros

Macros for catching pattern failure

Example:

{-# LANGUAGE Macro #-}
import Control.Exception.Macro;
a :: Int -> Int -> Int;
a 0 x = x;
a 1 x = x + x;
b :: Int -> Int -> Either String Int;
b = _Catch 2 a;
c :: Int -> Int -> IO Int;
c = _CatchIO 2 a;
d :: Int -> IO (Int -> Int);
d = _CatchIO 1 a;
e :: [String];
e = ["hello", "world", undefined];
f :: IO [String];
f = _CatchStrictIO 0 e do {
  case _This of {
    [] <- _Stop;
    h : t <- do {
      h;
      _Again t;
    };
  };
};

Meanings:

b 0 = Right;
b 2 = const $ Left "pattern match error";
c 0 = return;
c 2 = const $ fail "pattern match error";
d 0 = return id;
f = fail "undefined";

Note that _Catch and so on are macros, not functions. A macro is not a first-class value in the program, and cannot be used at run-time, but can have operations that a function doesn't have.

When calling the new function created by the macro, errors are converted to the return value instead (a function could not read undefined values, but a macro could change it into a different function so that it is not undefined).

You could specify strictifying with do-notation to ensure everything in there is defined before returning a value, so that an undefined value will be caught ahead of time.

User errors and pattern match errors can be caught even in a pure code, but out of memory error can only be caught in I/O actions.