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 14:00

I came up with something like this:

firstRow                 = U (repeat 0) 0 (1 : repeat 0)
rule       (U (a:_) b _) = a + b
getPascals (U _ _ rs)    = takeWhile (/= 0) rs

main = mapM_ print $ take 10
     $ map getPascal
     $ iterate (=>> rule) firstRow


If I understand right, though, this is exactly the definition you didn't want. This is the one that makes sense, though: the big mistake you're making is thinking U has a "grid-like" shape, while it's really a "tape" shape, which is really perfect for a single row of Pascal's triangle:

... 0 0 0 0 <0> 1 0 0 0 ...
... 0 0 0 0 <0> 1 1 0 0 ...
... 0 0 0 0 <0> 1 2 1 0 ...
... 0 0 0 0 <0> 1 3 3 1 ...
etc.


In other words: did you even think about >>10's answer?

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