9. 衝突したら?
• 上書きされることはなく、エラーになる。
– 当然っちゃ当然
– 実⾏行行されるまでは発覚しない…
Prelude> import Data.Map
Prelude Data.Map> null "a"
<interactive>:1:1:
Ambiguous occurrence `null'
It could refer to either `Prelude.null', imported from Prelude
or `Data.Map.null', imported from Data.Map
10. 標準モジュールの関数で問題を解く (1)
• ⽂文字列列から単語のリスト (Data.List.words)
Prelude Data.List> words "hey thease are the words in this sentence”
Prelude Data.List> words "hey thease are the words in this sentence"
※words は Prelude が再エクスポートしてるので、import せずとも使える
(importしたものをそのまま再度度エクスポートすることができ、この場合は衝突しない)
• グループ化する (Data.List.group)
Prelude Data.List> group [1,1,1,1,2,2,2,2,3,3,2,2,2,5,6,7]
Prelude Data.List> group ["boom","bip","bip","boom","boom”]
• ソートする (Data.List.sort)
Prelude Data.List> sort [5,4,3,7,2,1]
Prelude Data.List> sort ["boom","bip","bip","boom","boom”]
11. 再エクスポート
module A (
words
スコープにあるものがエクスポートされる
)
where
import Data.List
module A (
モジュールにあるものが⼀一括で
module Data.List
再エクスポートされる
)
where
import Data.List Q. hiding つかえたら便便利利なんだけど?
A. 書けないです
12. 3つあわせて -> 単語を数える
• こういう関数ができます。 -> work01.hs
*Main> wordNums "wa wa wee wa wa wa"
[("wa",5),("wee",1)]
• 関数合成を有効に使って、みやすく。
• ※全く関係ないけど :edit 便便利利すね。
21. 標準モジュールの関数で問題を解く (5)
• 次に、この関数を使って、
find (Data.List) で探す。
Prelude Data.List> :t find
find :: (a -> Bool) -> [a] -> Maybe a
• Maybe a
失敗することがあるという値。
⾃自分で作るときは、Just を使う。
22. Maybeの値を使おうとすると…
*Main Data.List> firstTo40
Just 49999
it :: Maybe Int
Maybe だからそのまま⼊入らない
(0.01 secs, 1581784 bytes)
*Main Data.List> digitSum it
<interactive>:1:10:
Couldn't match expected type `Int' with actual type `Maybe
Int'
In the first argument of `digitSum', namely `it'
In the expression: digitSum it
In an equation for `it': it = digitSum it
(0.00 secs, 1588312 bytes)
23. Maybeの値を使うには
• Data.Maybe.fromJustを使えばいい
*Main Data.List> import Data.Maybe
(0.00 secs, 2109848 bytes)
*Main Data.List Data.Maybe> firstTo40
Just 49999
it :: Maybe Int
(0.01 secs, 2115376 bytes)
*Main Data.List Data.Maybe> digitSum $ fromJust it
40
it :: Int
(0.01 secs, 2119672 bytes)