Search code examples
haskellpascals-triangle

pascal triangle in haskell nested lists


im trying to get the kth row in every list in the pascal list. For example pascal 4 would get the 4nd element in every row. So it would return 1,4,10,20... etc. I understand how to construct an infinite pascal list which is what outputs below, but im unsure of how to get a nth element in each nested list. any suggestions? i was thinking of using map, but im not necessarily mapping a function here which is throwing me off a bit. thank you.

// im trying to get pascal k to return the nth element of every row in the triangle
pascal n = map(\n -> ??) take n pascal 
pascal_infite = [1] : map (\l -> zipWith (+) (l ++ [0]) (0:l)) pascal_infinite

Solution

  • To get the kth row:

    >>> pascal_infinite !! 4
    [1,4,6,4,1]
    

    To get all rows from [0..k]:

    >>> map (pascal_infinite !!) [0..4]
    [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
    

    To get all rows from [0..k] fast:

    >>> take (4+1) pascal_infinite
    [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
    

    Whoops, misread the question a bit. To get what you're asking for, you should probably construct just use the good old n choose k formula or something similar if you're concerned about speed.

    If this is just an exercise, disregarding speed, here's one way:

    pascal n = map (!! n) $ drop n pascal_infinite
    

    Then simply sample a couple of the 4th elements:

    >>> take 8 $ pascal (4-1)
    [1,4,10,20,35,56,84,120]