[plt-scheme] How to fold it

From: Jordan Johnson (jmj at fellowhuman.com)
Date: Sat May 16 04:06:58 EDT 2009

This feels clunky to me, but how about:

(define (slide ls)
   (reverse (foldl (lambda (x ls)
                     ;; e.g.: 2 '((0 1) (0)) ==> ((0 1 2) (0 1) (0))
                     (if (null? ls)
                       (list (list x))
                       (cons (append (car ls) (list x))
                             ls)))
                   '()
                   ls)))

I also tried it as an unfold, which was cute by comparison, at the  
cost of some reversing:

(require srfi/1)

(define (slide2 ls)
   (unfold-right null?
                 reverse
                 rest
                 (reverse ls)))

Cheers,
jmj

On May 15, 2009, at 8:04 PM, wooks wrote:

> ;;slide :: [*] -> [[*]]
> ;;Given a list like '(0 1 2 3 4) produces '((0) (0 1) (0 1 2) (0 1 2
> 3) (01 2 3 4))
> (define slide
>   (lambda (a-list)
>     (cond
>       [(empty? a-list) empty]
>       [else (cons (list (first a-list))
>                   (map (lambda (x) (cons (first a-list) x))
>                        (slide (rest a-list))))])))
>
> This code is in the spirit of HTDP 12.4.2. The map prefixes the
> inductive case with the first of the list and
>
>         cons (list (first a-list))
>
> was what was required to get from what I had to what I wanted.
>
> It looks like something that should be foldable. How to get there?
>
> _________________________________________________
>   For list-related administrative tasks:
>   http://list.cs.brown.edu/mailman/listinfo/plt-scheme



Posted on the users mailing list.