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