From: Andrej Bauer <Andrej.Bauer@fmf.uni-lj.si>
To: Caml <caml-list@inria.fr>
Subject: Local references in Ocaml vs. state in Haskell
Date: Fri, 23 Nov 2007 11:16:00 +0100 [thread overview]
Message-ID: <4746A860.3000106@fmf.uni-lj.si> (raw)
I have some programs written in ocaml that use references. I wanted to
translate them to Haskell, but since I am not an active Haskell user, I
got stuck with a very simple problem, namely, that the state monad in
Haskell provides _global_ references while ocaml has _local_ references.
Suppose in ocaml I have this:
(* Does a functional [f] look at its argument [a]? *)
let touched f a =
let flag = ref false in
let _ = f (fun n -> flag := true; a n) in
!flag
"touched f a" evaluates "f a" and records the fact that f actually
evaluated a at some argument. Note that flag is a local reference, so f
does not have access to it.
Using a global flag does not work:
let flag = ref false
let touched' f a =
flag := false ;
let _ = f (fun n -> flag := true; a n) in
!flag
Now we can write an f which touches its argument but fools touched' by
reversing the value of flag.
let f a =
let y = a 42 in
touched := false ; y
If I try to use the State monad I will get a global reference threaded
thrugh the computation, and f will have access to it. I want a local
reference that is inaccessible outside its lexical scope. I am probably
missing something obvious about Haskell.
I am hoping that even though this is a question about Haskell, you won't
mind, as it gives everyone on this list an opportunity to show how ocaml
is superior to Haskell. Just kidding :-)
Andrej
next reply other threads:[~2007-11-23 10:15 UTC|newest]
Thread overview: 2+ messages / expand[flat|nested] mbox.gz Atom feed top
2007-11-23 10:16 Andrej Bauer [this message]
2007-11-23 15:50 ` [Caml-list] " Jeff Polakow
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=4746A860.3000106@fmf.uni-lj.si \
--to=andrej.bauer@fmf.uni-lj.si \
--cc=Andrej.Bauer@andrej.com \
--cc=caml-list@inria.fr \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox