Re: useful list functions
- From: Peter Lund <firefly diku dk>
- To: John Cupitt <john cupitt ng-london org uk>
- Cc: gtk-devel-list gnome org, Maciej Stachowiak <mjs eazel com>
- Subject: Re: useful list functions
- Date: Mon, 7 Aug 2000 15:06:21 +0200 (METDST)
On Mon, 7 Aug 2000, John Cupitt wrote:
First off: I love functional programming languages -- I've done my share
of programming imperative languages (since the mid-eighties) but I find
that I'm far more productive in ML than in C. Part of this is because of
a nicer type system, pattern matching, automatic memory management and the
ability to use recursion in real-world programs -- part of it is due to
the wonderful higher-order functions available in the standard libraries.
If I wrote the functions John and I suggest, would they stand a chance at
getting included?
----
> Maciej Stachowiak wrote:
> > /* Just like `map' in Lisp, Scheme or Perl, i.e. like for_each but
> > return a list of the results. (non-destructive) */
> gpointer slist_map( GSList *list,
> ListMapFn user_func, gpointer user_data );
Great -- I like having the bail-out option, could be used for simulating
exceptions :)
> typedef gpointer (*ListFoldFn)( gpointer, gpointer, gpointer );
> gpointer slist_fold( GSList *list,
> gpointer start, ListFoldFn user_function, gpointer user_data );
This is even better stuff :)
> Using fold you can find the maximum value in a list, write Maciej's
> _map() function, sum a list, erm, and other stuff.
Yep, lots of other stuff :)
(I have programmed some small programs in ML, only up to a couple of
thousand lines -- they would have been so much longer in low-level
language like C using only the standard libraries)
> There are a few variants as well: slist_map2 and slist_fold2 take two
> user_data arguments. slist_map_rev() maps in reverse order.
> slist_foldr() folds a list with a right-associative function.
>
Great :)
What about equivalents to the take, drop, filter, mappartial, and
partition functions often found in functional programming languages?
take(l:list, n:integer) -- returns a list containing the first n elements
in l.
drop(l:list, n:integer) -- returns a list with the first n elements
dropped from l.
filter(l:list, f:filterfunction) -- returns a list of the elements for
which the filterfunction returns true.
mappartial(l:list, f:optmapfunc) -- returns a list of the elements in l
mapped onto a new domain (i.e. after
conversion by the mapfunc). Elements
can be dropped/filtered out by the
mapfunction.
These should go a long way towards eliminating loops in (the application
programmers' part of) GTK+ programs.
-Peter
Code is much like elephant dung. The more code, the more bugs.
You have to let it rest a while to make sure that the bugs are gone (and large
heaps rot slowly).
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]