Skip to content

Instantly share code, notes, and snippets.

@iyahoo
Created July 20, 2016 03:03
Show Gist options
  • Save iyahoo/55e7e9c8864b64ee856d8c9797283566 to your computer and use it in GitHub Desktop.
Save iyahoo/55e7e9c8864b64ee856d8c9797283566 to your computer and use it in GitHub Desktop.

H会演習

1. 以下に適切なコードを埋めよ

文章を読み込み、その単語と頻出度を返すwordNums関数を書け。 ただし、モジュールData.Listに含まれる関数を使用して良い。

import Data.List
wordNums :: String -> [(String, Int)]
wordNums str = map (\gs -> (head gs, length gs)) grouped_str 
  where grouped_str = (group $ sort $ words str)

2. 以下に適切なコードを埋めよ

任意のリストに対して部分リストが含まれるかどうかを調べる関数isInを定義せよ。 ただし、モジュールData.Listに含まれる関数を使用して良い。

import Data.List
isIn :: (Eq a) => [a] -> [a] -> Bool
isIn xs ys = elem xs $ map (\subset_ys -> (take (length xs) subset_ys)) (tails ys)

3. 以下に適切なコードを埋めよ

1,2 に出てきた関数を自力で実装せよ group, words, tails, isPrefix

tails' :: [a] -> [[a]]
tails' [] = [[]]
tails' (x:xs) = [(x:xs)] ++ tails' xs

group' :: Eq a => [a] -> [[a]]
group' [] = []
group' [x] = [[x]]
group' (x:xs) = [takeWhile (== x) (x:xs)] ++ group' rest_xs
  where rest_xs = dropWhile (== x) xs

4. 以下に適切なコードを埋めよ

Maybeとは何か、Maybeを利用した関数を何か一つ実装せよ

-- Maybe は型のひとつであり Just a と nothing という値を持つ
-- Maybe 型を返す関数を使用する場合は Nothing の場合のエラー処理をすることで安全に扱え、
-- また自分が実装する関数で Maybe 型を使うことで、使用者に対して失敗する可能性があることを
-- 容易に伝えることができる
safe_head :: [a] -> Maybe a
safe_head (x:_) = Just x
safe_head [] = Nothing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment