Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Comonadically building Pascal's Triangle

Name: Anonymous 2012-10-18 12:18

I was reading [1] and one of the comments suggested implementing Pascal's Triangle comonadically as an exercise. However the approach I'm trying to take doesn't work out since I can't find an un-arbitrary implementation for coreturn of T's Even constructor, and I /don't/ want to represent Pascal's Triangle with a 2D grid, as in [1]'s U type.


class Functor w => Comonad w where
    coreturn :: w a -> a
    cojoin   :: w a -> w (w a)
    (=>>)    :: w a -> (w a -> b) -> w b
    x =>> f = fmap f $ cojoin x

data T x = Odd  [x]   x   [x]
         | Even [x] (x,x) [x]

instance Functor T where
    fmap f (Odd  l    m    r) = Odd  (fmap f l)    (f m)     (fmap f r)
    fmap f (Even l (ml,mr) r) = Even (fmap f l) (f ml, f mr) (fmap f r)

instance Comonad T where
    coreturn (Odd  _ m _) = m
    coreturn (Even ? ? ?) = ?


So, what can I do? Is there even a sensible instance of Comonad for the representation I've chosen, or do I just /have/ to use a grid-like structure for the data type?

In joyful anticipation of your illuminating comments, a fellow /prog/rider.

[1] http://blog.sigfpe.com/2006/12/evaluating-cellular-automata-is.html

Name: Anonymous 2012-10-19 0:10

If not sure if this is what you are after, but this implementation takes the current list, appends and prepends ones to it, generates a list of adjacent pairs, and then maps it with apply +.

(2 2) -> (1 2 2 1) -> ((1 2) (2 2) (2 1)) -> (3 4 3)


(define (rev-adj-pairs lis acc)
  (if (or (null? lis) (null? (cdr lis)))
    acc
    (rev-adj-pairs (cdr lis)
                   (cons (list (car lis) (cadr lis))
                         acc))))

(define (adj-pairs lis acc)
  (reverse (rev-adj-pairs lis acc)))

(define (adj-pairs-with-caps first-elem lis last-elem)
  (if (null? lis)
    (list first-elem last-elem)
    (let* ((lis-with-first-elem (cons first-elem lis))
           (rev-adj-pairs-with-first-elem (rev-adj-pairs lis-with-first-elem '()))
           (rev-adj-pairs-with-all (cons (list (cadar rev-adj-pairs-with-first-elem) last-elem) rev-adj-pairs-with-first-elem))
           (adj-pair-all (reverse rev-adj-pairs-with-all)))
      adj-pair-all)))

(define (pascal-next gen)
  (map (lambda (pair) (apply + pair))
       (adj-pairs-with-caps 1 gen 1)))

(define (collect-orbit f x i acc)
  (if (= i 0)
    (reverse acc)
    (let ((v (f x)))
      (collect-orbit f v (- i 1) (cons v acc)))))

(collect-orbit pascal-next '(1) 10 '())

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List