実例によるPureScript 7 章
Applicative の章。難易度が上がって来ている気がする。演習はなんとかこなせたが、正直まだ全然適切に利用できる気がしない。慣れるものなんだろうか。
main :: Effect Unit
main = do
logShow $ lift2 (+) (Just 2) (Just 3)
logShow $ lift2 (+) (Just 2) Nothing
logShow $ lift2 (-) (Just 2) (Just 3)
logShow $ lift2 (-) (Just 2) Nothing
logShow $ lift2 (*) (Just 2) (Just 3)
logShow $ lift2 (*) (Just 2) Nothing
logShow $ lift2 (/) (Just 6) (Just 3)
logShow $ lift2 (/) (Just 2) Nothing
(Just 5)
Nothing
(Just -1)
Nothing
(Just 6)
Nothing
(Just 2)
Nothing
難しいが、lift3 は
forall a b c d f. Apply f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
となっているので、最初の <$> が適用された状態では、コンテナ内で残り 2 引数待ち状態になる。
f (b -> c -> d) -> f b -> f c -> f d
<*> で f b、f c を渡せば f d が返ってくるので整合している、、で説明になっているのか??
combineMaybe :: forall a f. (Applicative f) => Maybe (f a) -> f (Maybe a)
combineMaybe Nothing = pure Nothing
combineMaybe (Just x) = (pure Just) <*> x
validateState :: String -> V Errors String
validateState state = matches "State" stateRegex state
stateRegex :: Regex
stateRegex = unsafeRegex "^\\w{2}$" noFlags
validateNoSpace :: String -> String -> V Errors String
validateNoSpace field = matches field noSpaceRegex
noSpaceRegex :: Regex
noSpaceRegex = unsafeRegex "^(?!.* ).*$" noFlags
data Tree a = Leaf | Branch (Tree a) a (Tree a)
instance showTree :: Show a => Show (Tree a) where
show Leaf = "<Leaf>"
show (Branch tl a tr) = "<" <> show tl <> ", " <> show a <> ", " <> show tr <> ">"
instance functorTree :: Functor Tree where
map _ Leaf = Leaf
map f (Branch tl a tr) = Branch (map f tl) (f a) (map f tr)
instance fodableTree :: Foldable Tree where
foldr _ init Leaf = init
foldr func init (Branch tl a tr) = foldr func (func a (foldr func init tr)) tl
foldl _ init Leaf = init
foldl func init (Branch tl a tr) = foldl func (func (foldl func init tl) a) tr
foldMap _ Leaf = mempty
foldMap func (Branch tl a tr) = (foldMap func tl) <> (func a) <> (foldMap func tr)
instance treeTraverse :: Traversable Tree where
traverse _ Leaf = pure Leaf
traverse func (Branch tl a tr) = Branch <$> traverse func tl <*> func a <*> traverse func tr
sequence = traverse identity
--sequence Leaf = pure Leaf
--sequence (Branch tl a tr) = Branch <$> sequence tl <*> a <*> sequence tr
フィールドの定義も Maybe Address に変更する必要がある。validateAddress は以下のようにしたら動いた。
validateAddress :: Maybe Address -> V Errors (Maybe Address)
validateAddress addr = traverse (\a -> address <$> nonEmpty "Street" a.street
<*> nonEmpty "City" a.city
<*> lengthIs "State" 2 a.state) addr
この記事が気に入ったらサポートをしてみませんか?