Version française
Home     About     Download     Resources     Contact us    
Browse thread
backtracking monad
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Pietro Abate <Pietro.Abate@a...>
Subject: backtracking monad
hi all,

Can anyone help me to 'translate' this piece of haskell code [1] in
ocaml ? 

I'm trying to learn how to program in monad style, but since I don't
know haskell syntax (and almost all examples about monads are in
haskell), I have some problems to understand what's going on here...
I've got the general idea about monads, but the haskell syntax confuses
me.

Moreover I've also a general question about monads... I've the sensation
that monads implementations are not tail-recursive. Is there a big
overhead in using monads Vs Continuations (CPS) ?

Where can I find a collections of basic monads (state, backtracking,
continuation, etc) written in ocaml ? 

thanks,
:)
p

-------------------

(* backtracking monad *)
type MBt a = M [a]
x `bindBt` f = x `bindM` \vs ->
             foldr orelseBt failBt (map f vs)

liftBt :: M a -> MBt a
liftBt m = m `bindM` \v -> unitM [v]

infixl 5 `apM`
apM :: M (a -> b) -> M a -> M b
fm `apM` fx = fm `bindM` \f -> 
              fx `bindM` \x ->
              unitM (f x)

orelseBt :: MBt a -> MBt a -> MBt a
x `orelseBt` y = unitM (++) `apM` x `apM` y

failBt :: MBt a
failBt = unitM []

-------------------

this is my (failed) attempt ...

(* state monad *)
module M = struct
  type ('x, 'a) t = ('a -> 'x) -> 'x
  let bind m f x = m (fun a -> f a x)
  let return x = fun s -> x, s
end

(* backtracking monad *)
module BtM = struct
  (* this list should be a lazy list *)
  type ('x ,'a) t = ('a, 'x list) M.t
  let return x = [x]
  let fail = return []
  let orelse = ???
  let bind m x f = List.fold_left orelse fail (List.map f x)
end

(* recursive mondad ?? *)

-------------------

(* recursive mondad ?? *)
type MRBt a = M (Ans a)
data Ans a = Ans a (MRBt a) | NoAns
x `bindRBt` f = x `bindM` \y -> case y of
             NoAns -> failRBt
             Ans v x' -> f v `orelseRBt` (x' `bindRBt` f)

liftRBt m = m `bindM` \v -> unitM (Ans v failRBt)

failRBt = unitM NoAns
x `orelseRBt` y = x `bindM` \z -> case z of
               NoAns -> y
               Ans v x' -> unitM (Ans v (x' `orelseRBt` y))

-------------------

[1] http://www.math.chalmers.se/~augustss/AFP/monads.html

-- 
++ Blog: http://blog.rsise.anu.edu.au/?q=pietro
++ 
++ "All great truths begin as blasphemies." -George Bernard Shaw
++ Please avoid sending me Word or PowerPoint attachments.
   See http://www.fsf.org/philosophy/no-word-attachments.html