On Wed, Aug 10, 2005 at 06:34:19PM +0000, Alan Post wrote:
> In article <20050810173844.GB6103@...>, Richard W. M. Jones wrote:
> >
> > Well OK, but we don't even have a function to do the
> > int list -> (int * int) list transformation.
>
> A fold using a ref would work, yes?
Something like that might, but the whole point of HOFs is to avoid
having to write ugly hacks all the time :-)
Here are my two functions for taking pairs of elements from lists.
FWIW, I have used both of these patterns in real code on more than one
occasion, although the first one is used a lot more frequently than
the second (for disaggregating our counted data):
# let rec take_pairs = function
| [] | [_] -> invalid_arg "take_pairs"
| [x; y] -> [x, y]
| x :: (y :: _ as xs) ->
(x, y) :: take_pairs xs;;
val take_pairs : 'a list -> ('a * 'a) list = <fun>
# take_pairs [1; 2; 3; 4; 5; 6; 7; 8];;
- : (int * int) list =
[(1, 2); (2, 3); (3, 4); (4, 5); (5, 6); (6, 7); (7, 8)]
# let rec take_in_twos = function
| [] -> []
| [_] -> invalid_arg "take_in_twos"
| x :: y :: xs -> (x, y) :: take_in_twos xs;;
val take_in_twos : 'a list -> ('a * 'a) list = <fun>
# take_in_twos [1; 2; 3; 4; 5; 6; 7; 8];;
- : (int * int) list = [(1, 2); (3, 4); (5, 6); (7, 8)]
Rich.
--
Richard Jones, CTO Merjis Ltd.
Merjis - web marketing and technology - http://merjis.com
Team Notepad - intranets and extranets for business - http://team-notepad.com
|