Created
June 28, 2013 15:21
-
-
Save karszawa/5885483 to your computer and use it in GitHub Desktop.
すごいHaskell読書会 in 大阪 #1 練習問題解いてみた
This file contains 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
{- 以下の関数を定義しなさい | |
* null | |
* sum | |
* product | |
* elem | |
* Pythonのスライス ex) slice 2 5 [1..7] # => [3, 4, 5] | |
* フィボナッチ数列のn番目の数を返す関数 | |
* FizzBuzzのn項目からm項目までを返す関数 | |
-} | |
null' :: (Eq a) => [a] -> Bool | |
null' v = v == [] | |
sum' :: [Int] -> Int | |
sum' = foldr (\x acc -> x + acc) 0 | |
product' :: [Int] -> Int | |
product' = foldr (\x acc -> x * acc) 1 | |
elem' :: (Eq a) => a -> [a] -> Bool | |
elem' e = foldr (\x acc -> acc || e == x) False | |
slice :: Int -> Int -> [a] -> [a] | |
slice 0 0 _ = [] | |
slice 0 b (x:xs) = x : slice' 0 (b-1) xs | |
slice a b (x:xs) = slice' (a-1) (b-1) xs | |
fibonacci :: Int -> Int | |
fibonacci i = snd $ iterate (\(a, b) -> (b, a+b)) (1, 1) !! i | |
fizzbuzz :: Int -> Int -> [String] | |
fizzbuzz n m | |
| n == m = [] | |
| otherwise = showFizzbuzz n : fizzbuzz (n+1) m | |
where showFizzbuzz n | |
| n `mod` 15 == 0 = "FizzBuzz" | |
| n `mod` 3 == 0 = "Fizz" | |
| n `mod` 5 == 0 = "Buzz" | |
| otherwise = show n | |
{- 以下に示す,「良い整数」のうち一の位が0でないものを3桁の整数の中から4つ探しなさい | |
* 3けたの整数を2つの整数に分けてその和を考えると,常にもとの整数の約数になっている | |
* 330は3と30に分けても,33と0に分けても和が330の約数になっています.このため,330は「良い整数」となります.ですが,702は7と02に分けた場合は約数になりますが,70と2に分けてしまうと約数になりません.よって,702は「良い整数」ではありません | |
-} | |
splitNumber :: Int -> [(Int, Int)] | |
splitNumber n = | |
let s = show n | |
e = length s - 1 | |
in map ((\(a, b) -> (read a :: Int, read b :: Int)) . (flip splitAt $ s)) [1..e] | |
isGoodNumber :: Int -> Bool | |
isGoodNumber n = | |
n `mod` 10 /= 0 && (and $ map ((\x -> n `mod` x == 0) . (\(a, b) -> a + b)) $ splitNumber n) | |
goodNumbers :: [Int] | |
goodNumbers = filter isGoodNumber [100..999] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment