Created
December 21, 2017 11:57
-
-
Save ardfard/f49c6e64d595020b2299fe8c42055e31 to your computer and use it in GitHub Desktop.
FP Guild exercise part 1
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
| #! /usr/bin/env stack | |
| -- stack --resolver lts-9.5 script | |
| ---------- EX 1 ------------------- | |
| pascal :: Int -> Int -> Int | |
| pascal c r | |
| | c == 0 = 1 | |
| | r == c = 1 | |
| | otherwise = pascal (c - 1) (r - 1) + pascal c (r - 1) | |
| test1 :: Int -> Int -> Int -> String | |
| test1 c r res = "pascal " ++ show c ++ " " ++ show r ++ " == " ++ show res ++ " -> " ++ show (pascal c r == res) | |
| ex1 = do | |
| mapM_ putStrLn [ test1 0 2 1 | |
| , test1 1 2 2 | |
| , test1 2 2 1 | |
| , test1 1 3 3 | |
| , test1 2 3 3 ] | |
| ------------------------------------ | |
| ---------- EX2 -------------------------- | |
| balance :: String -> Bool | |
| balance i = go i 0 == 0 | |
| where go [] state = state | |
| go (x:xs) state | |
| | state > 0 = state | |
| | x == '(' = go xs (state - 1) | |
| | x == ')' = go xs (state + 1) | |
| | otherwise = go xs state | |
| test2 :: String -> String | |
| test2 i = "\"" ++ i ++ "\" is " ++ (if balance i then "" else "not") ++ " balanced" | |
| testInputs = [ "(if (zero? x) max (/ 1 x))" | |
| , "I told him (that it’s not (yet) done). (But he wasn’t listening)" | |
| , ":-)" | |
| , "())(" | |
| ] | |
| ex2 = mapM_ (putStrLn . test2) testInputs | |
| ------------------------------------------- | |
| --------- EX3 ---------------------------- | |
| countChange :: Int -> [Int] -> Int | |
| countChange 0 _ = 1 | |
| countChange _ [] = 0 | |
| countChange n (x:xs) = sum [countChange (n - i*x) xs | i <- [1.. div n x]] | |
| ex3 = putStrLn $ "Coin change for 4 with denom [1,2] -> " ++ show (countChange 4 [1, 2]) | |
| ----------------------------------------- | |
| main = do | |
| ex1 | |
| ex2 | |
| ex3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment