From: Brian Hurt <bhurt@janestcapital.com>
To: Fernando Alegre <fernando@cc.gatech.edu>
Cc: Erik de Castro Lopo <mle+ocaml@mega-nerd.com>, caml-list@yquem.inria.fr
Subject: Re: [Caml-list] Combinatorics in a functional way
Date: Wed, 21 Feb 2007 09:36:29 -0500 [thread overview]
Message-ID: <45DC58ED.6080103@janestcapital.com> (raw)
In-Reply-To: <20070221134635.GA28981@gaia.cc.gatech.edu>
A good, functional, generic solution:
type 'a queue = 'a list * 'a list;;
let init lst : 'a queue = lst, [];;
let is_empty : 'a queue -> bool = function
| [], [] -> true
| _ -> false
;;
let rem_head : 'a queue -> 'a * 'a queue = function
| (h::t), b -> h, (t, b)
| [], b ->
match (List.rev b) with
| h :: t -> h, (t, [])
| [] -> invalid_arg "rem_head on empty queue!"
;;
let append_tail ((s, b) : 'a queue) x : 'a queue = s, (x :: b);;
let fold_permute_list f accum lst =
let rec loop1 acc t q n =
if is_empty q then
f acc (List.rev t)
else
let rec loop2 acc q i =
if i == 0 then
acc
else
let h, q = rem_head q in
let acc = loop1 acc (h :: t) q (n-1) in
loop2 acc (append_tail q h) (i-1)
in
loop2 acc q n
in
loop1 accum [] (init lst) (List.length lst)
;;
Okasaki should be required reading.
Brian
next prev parent reply other threads:[~2007-02-21 14:36 UTC|newest]
Thread overview: 10+ messages / expand[flat|nested] mbox.gz Atom feed top
2007-02-21 9:36 Erik de Castro Lopo
2007-02-21 10:36 ` [Caml-list] " David Baelde
2007-02-21 12:17 ` Frédéric van der Plancke
2007-02-21 11:06 ` Pietro Abate
2007-02-21 13:19 ` Jacques Carette
2007-02-21 11:29 ` Nicolas Pouillard
2007-02-21 12:24 ` Gabriel Kerneis
2007-02-21 13:46 ` Fernando Alegre
2007-02-21 14:36 ` Brian Hurt [this message]
2007-02-22 10:01 ` Erik de Castro Lopo
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=45DC58ED.6080103@janestcapital.com \
--to=bhurt@janestcapital.com \
--cc=caml-list@yquem.inria.fr \
--cc=fernando@cc.gatech.edu \
--cc=mle+ocaml@mega-nerd.com \
/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