Real World Haskell Chapter3
Nullable.hsはNulllabel.hsのtypo?
--Nullable.hs data Maybe a = Just a | Nothing someBool = Just True someString = Just "something" wrapped = Just (Just "wrapped")
写経すると以下のエラー.
よく分からんが,定義が重複しているみたい?
[1 of 1] Compiling Main ( Nullable.hs, interpreted ) Nullable.hs:5:11: Ambiguous occurrence `Just' It could refer to either `Main.Just', defined at Nullable.hs:2:15 or `Prelude.Just', imported from Prelude
--Nullable.hs data Maybe a = Just a | Nothing someBool = Main.Just True someString = Main.Just "something" wrapped = Main.Just (Main.Just "wrapped")
Scopeを制限してみようと,以上に改造してみた.
読み込みはできるけど,以下のエラーが発生する.
MaybeとかJustとかよく分からん.
[1 of 1] Compiling Main ( Nullable.hs, interpreted ) Ok, modules loaded: Main. *Main> some someBool someString *Main> someBool <interactive>:1:0: No instance for (Show (Main.Maybe Bool)) arising from a use of `print' at <interactive>:1:0-7 Possible fix: add an instance declaration for (Show (Main.Maybe Bool)) In a stmt of a 'do' expression: print it
分からないところは飛ばして練習問題.
--ListADT.hs data List a = Cons a (List a) | Nil deriving (Show) fromList :: [t] -> List t fromList (x:xs) = Cons x (fromList xs) fromList [] = Nil toList :: List t -> [t] toList Nil = [] toList xs = [headList xs] ++ toList (tailList xs) headList (Cons x _) = x tailList (Cons _ xs) = xs
2問目はMaybeを使えと書いてあるが...
ここで挫折の予感がします.
3.9.2 Where節
lend関数とlend2関数の動作が全然違う.
ということで,同じ動作の関数をlend3として作ってみた.
--Lending.hs lend amount balance = let reserve = 100 newBalance = balance - amount in if balance < reserve then Nothing else Just newBalance lend2 amount balance = if amount < reserve * 0.5 then Just newBalance else Nothing where reserve = 100 newBalance = balance - amount lend3 amount balance = if balance < reserve then Nothing else Just newBalance where reserve = 100 newBalance = balance - amount
しかも,lend2は引数によってはsegv起こすし...
初心者の私には原因がわかりません.
[1 of 1] Compiling Main ( Lending.hs, interpreted ) Ok, modules loaded: Main. *Main> lend2 15 10 Just (-[1] 6301 segmentation fault ghci