Simple Pascal-triangle implementations

-- The first version can output a row of Pascal's triangle:
import System.Environment(getArgs)

pas 0       = [1]
pas n | n>0 = let l = pas (n-1) in zipWith (+) (0:l) (l++[0])

main = do
    [s] <- getArgs
    print . pas $ read s



-- The second revision can output a certain number of rows of the triangle:
import System.Environment(getArgs)

pas = iterate nextline [1] where
    nextline l = zipWith (+) (0:l) (l++[0])

main = do
    [s] <- getArgs
    putStr . unlines . map show $ take (read s+1) pas



-- And the last monolith solves a very simple homework assignment:
import Data.List(intersperse)
import System.Environment(getArgs)

pas 0 = [1]
pas n = let l = pas (n-1) in zipWith (+) (0:l) (l++[0])

strPas s = do
    let n = read s
    if n<0 || n>30 then
        fail "Pascal out of range"
    else do
        let list = concat . intersperse " " . map show
        return (n, list $ pas n)

main = do
    l <- getArgs
    case l of
        [s] -> do (_,o) <- strPas s
                  putStrLn o
        []  -> do s <- readFile "input.txt"
                  (n,o) <- strPas s
                  writeFile "output.txt" $ unlines [show n, o]

Comments

Popular posts from this blog

Hidden TFTP of TP-Link routers

Tftp secret of TL-WR740N uncovered

When both Google *and* AppStatus is down