Created
November 10, 2012 05:04
-
-
Save akanehara/4049995 to your computer and use it in GitHub Desktop.
すごいHaskell勉強会 in 大阪 練習問題
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
-- しゅくだい exercise1.hs | |
-- ここから(だいたい)2章までの知識縛り | |
-- 中身が任意の型であること以外要求しないので型制約なし | |
null' :: [a] -> Bool | |
null' xs = if length xs == 0 then True else False | |
-- (+) を使うので Num a と制約 | |
sum' :: Num a => [a] -> a | |
sum' xs = if null' xs then 0 else head xs + sum' (tail xs) | |
-- (*) を使うので Num a と制約 | |
product' :: Num a => [a] -> a | |
product' xs = if null' xs then 1 else head xs * product' (tail xs) | |
-- (==) を使うので Eq a と制約 | |
elem' :: Eq a => a -> [a] -> Bool | |
elem' x ys = if null' ys then False else x == head ys || elem' x (tail ys) | |
slice :: Int -> Int -> [a] -> [a] | |
slice a b xs = take b (drop (a - 1) xs) | |
-- 縛り解除 | |
-- 3 * 5 を利用せずにパターンマッチで場合分けしてみた | |
fizzBuzz :: Int -> Int -> [[Char]] | |
fizzBuzz a b = map fizzBuzzTerm [a .. b] | |
where | |
fizzBuzzTerm n = | |
let isFizz = n `mod` 3 == 0 | |
isBuzz = n `mod` 5 == 0 | |
in case (isFizz, isBuzz) of -- View Pattern 使うとコンパクトになる? | |
(False, False) -> show n | |
(True, False) -> "fizz" | |
(False, True) -> "buzz" | |
(True, True) -> "fizzbuzz" | |
-- あれ、5個出てきた | |
goodNums :: [Int] | |
goodNums = [ x | x <- [100..999], x `mod` 10 /= 0, isGood x ] | |
where | |
isGood n = | |
let s = show n | |
x = (read $ take 1 s) + (read $ drop 1 s) | |
y = (read $ take 2 s) + (read $ drop 2 s) | |
in (n `mod` x == 0) && (n `mod` y == 0) | |
-- Enum と [..] | |
-- 曜日 | |
data DayOfWeek = 日 | 月 | 火 | 水 | 木 | 金 | 土 | |
deriving (Enum, Show) | |
-- Enumのインスタンスになると [..] が使える | |
-- 平日 | |
weekday :: [DayOfWeek] | |
weekday = [月 .. 金] -- 数値と違って空白必須! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment