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