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