cannam@95: (* cannam@95: * Copyright (c) 1997-1999 Massachusetts Institute of Technology cannam@95: * Copyright (c) 2003, 2007-11 Matteo Frigo cannam@95: * Copyright (c) 2003, 2007-11 Massachusetts Institute of Technology cannam@95: * cannam@95: * This program is free software; you can redistribute it and/or modify cannam@95: * it under the terms of the GNU General Public License as published by cannam@95: * the Free Software Foundation; either version 2 of the License, or cannam@95: * (at your option) any later version. cannam@95: * cannam@95: * This program is distributed in the hope that it will be useful, cannam@95: * but WITHOUT ANY WARRANTY; without even the implied warranty of cannam@95: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the cannam@95: * GNU General Public License for more details. cannam@95: * cannam@95: * You should have received a copy of the GNU General Public License cannam@95: * along with this program; if not, write to the Free Software cannam@95: * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA cannam@95: * cannam@95: *) cannam@95: cannam@95: (************************************************************* cannam@95: * Monads cannam@95: *************************************************************) cannam@95: cannam@95: (* cannam@95: * Phil Wadler has many well written papers about monads. See cannam@95: * http://cm.bell-labs.com/cm/cs/who/wadler/ cannam@95: *) cannam@95: (* vanilla state monad *) cannam@95: module StateMonad = struct cannam@95: let returnM x = fun s -> (x, s) cannam@95: cannam@95: let (>>=) = fun m k -> cannam@95: fun s -> cannam@95: let (a', s') = m s cannam@95: in let (a'', s'') = k a' s' cannam@95: in (a'', s'') cannam@95: cannam@95: let (>>) = fun m k -> cannam@95: m >>= fun _ -> k cannam@95: cannam@95: let rec mapM f = function cannam@95: [] -> returnM [] cannam@95: | a :: b -> cannam@95: f a >>= fun a' -> cannam@95: mapM f b >>= fun b' -> cannam@95: returnM (a' :: b') cannam@95: cannam@95: let runM m x initial_state = cannam@95: let (a, _) = m x initial_state cannam@95: in a cannam@95: cannam@95: let fetchState = cannam@95: fun s -> s, s cannam@95: cannam@95: let storeState newState = cannam@95: fun _ -> (), newState cannam@95: end cannam@95: cannam@95: (* monad with built-in memoizing capabilities *) cannam@95: module MemoMonad = cannam@95: struct cannam@95: open StateMonad cannam@95: cannam@95: let memoizing lookupM insertM f k = cannam@95: lookupM k >>= fun vMaybe -> cannam@95: match vMaybe with cannam@95: Some value -> returnM value cannam@95: | None -> cannam@95: f k >>= fun value -> cannam@95: insertM k value >> returnM value cannam@95: cannam@95: let runM initial_state m x = StateMonad.runM m x initial_state cannam@95: end