Last active
December 15, 2015 15:19
-
-
Save WillNess/5281352 to your computer and use it in GitHub Desktop.
interleaved-pairs in Scheme and Haskell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| http://stackoverflow.com/questions/15730385/scheme-pairs-output/15731206#15731206 | |
| ipairs (x:xs) (y:ys) = (x,y) : g xs ys [map ((,) x) ys] where | |
| g (x:xs) (y:ys) ac = (x,y) : map head ac ++ g xs ys (map ((,) x) ys : map tail ac) | |
| ipairs1 (x:xs) (y:ys) = (x,y) : g xs ys [map ((,) x) ys] where | |
| g (x:xs) (y:ys) ac = map head (reverse ac) ++ (x,y) : g xs ys (map ((,) x) ys : map tail ac) | |
| In Scheme, | |
| (define (interleaved-pairs xs ys . args) | |
| (let ((x (stream-car xs)) | |
| (ac ())) | |
| (cond | |
| ((null args) | |
| (stream-cons (list x (stream-car ys)) | |
| (interleaved-pairs | |
| (stream-cdr xs) | |
| (stream-cdr ys) | |
| (stream | |
| (stream-map (lambda(y)(list x y)) (stream-cdr ys)))))) | |
| (else | |
| (set! ac (car args)) | |
| (stream-cons (list x (stream-car ys)) | |
| (stream-append (stream-map stream-car ac) | |
| (interleaved-pairs | |
| (stream-cdr xs) | |
| (stream-cdr ys) | |
| (stream-cons | |
| (stream-map (lambda(y)(list x y)) (stream-cdr ys)) | |
| (stream-map stream-cdr ac))))))))) | |
| This should produce results in slightly different order: `(1 1) (2 2) (1 2) (3 3) (2 3) (1 3) ...`. | |
| You tagged this as racket also. As far as I can see in | |
| [the Racket documentation](http://docs.racket-lang.org/reference/streams.html), | |
| it has `stream-first` in place of `stream-car`, etc. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment