単語を数える
• 文字列に対して単語をカウントしたい
• Data.Listのwords関数:空白で単語を区切る
GHCi> words "hey these are the words in this sentence"
["hey","these","are","the","words","in","this","sentence"]
GHCi> words "hey these are the words in this sentence"
["hey","these","are","the","words","in","this","sentence"]
• Data.Listのgroup関数: 隣接要素をグルーピング
GHCi> group [1,1,1,1,2,2,2,2,3,3,2,2,2,5,6,7]
[[1,1,1,1],[2,2,2,2],[3,3],[2,2,2],[5],[6],[7]]
各桁の合計を求める関数
import Data.Char
import Data.List
!
digitSum:: Int -> Int
digitSum = sum . map digitToInt . show
GHCi> :t show
show :: Show a => a -> String
GHCi> :t (map digitToInt)
(map digitToInt) :: [Char] -> [Int]
GHCi> :t sum
sum :: Num a => [a] -> a
GHCi> :t (sum . (map digitToInt) . show)
(sum . (map digitToInt) . show) :: Show a => a -> Int
Maybe a型の値
• NothingかJustxのどちらか
• Nothing
• 0個の要素を持っている = 何も持っていない という値
• 空リストに似ている
• Just x
• Maybe a型のxを保持していることを表現
39.
よく分からないので型を調べる
GHCi> Nothing
Nothing
GHCi> :tNothing
Nothing :: Maybe a
GHCi> Just "hey"
Just "hey"
GHCi> Just 3
Just 3
GHCi> :t Just "hey"
Just "hey" :: Maybe [Char]
GHCi> :t Just 3
Just 3 :: Num a => Maybe a
GHCi> :t Just True
Just True :: Maybe Bool
合計値をnとして一般化
import Data.List
import Data.Char
!
digitSum:: Int -> Int
digitSum = sum . map digitToInt . show
!
firstTo :: Int -> Maybe Int
firstTo n = find (x -> digitSum x == n) [1..]
GHCi> firstTo 27
Just 999
GHCi> firstTo 1
Just 1
GHCi> firstTo 13
Just 49
Map.lookupによる検索
GHCi> :t Map.lookup
Map.lookup:: Ord k => k -> Map.Map k a -> Maybe a
GHCi> Map.lookup "betty" phoneBook
Just "555-2938"
GHCi> Map.lookup "wendy" phoneBook
Just "939-8282"
GHCi> Map.lookup "grace" phoneBook
Nothing
54.
新しい番号を挿入して新しいMapを作る
GHCi> :t Map.insert
Map.insert:: Ord k => k -> a -> Map.Map k a -> Map.Map k a
GHCi> Map.lookup "grace" phoneBook
Nothing
GHCi> let newBook = Map.insert "grace" "341-9021" phoneBook
GHCi> Map.lookup "grace" newBook
Just "341-9021"