Traversable型クラス
左から右へなめて作用を各点ごとに評価可能な型クラス
Functor型クラスとFoldable型クラスを継承する
Haskell
hackage
code:hs
class (Functor t, Foldable t) => Traversable t where
traverse :: Applicative f => (a -> f b) -> t a -> f (t b)
sequenceA :: Applicative f => t (f a) -> f (t a)
mapM :: Monad m => (a -> m b) -> t a -> m (t b)
sequence :: Monad m => t (m a) -> m (t a)
table:4つのmethodを持つ
Applicative版 Monad版
traverse mapM
sequenceA sequence関数
traverseかsequenceAのいずれかを定義すればあとは自動的に決まる
Applicative版の方のいずれか1つを定義すれば良い
なので結局1つの定義で済むmrsekut.icon
traverseを定義することが多い
PureScript
pursuit
code:purs(hs)
class (Functor t, Foldable t) <= Traversable t where
traverse :: forall a b m. Applicative m => (a -> m b) -> t a -> m (t b)
sequence :: forall a m. Applicative m => t (m a) -> m (t a)
その他の関数
forM関数
mapMの引数を入れ替えた関数
code:hs
forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b)
forM = flip mapM
for関数
traverseの引数を入れ替えた関数
code:hs
for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b)
for = flip traverse
参考
第52回 データ構造を走査するためのTraversableクラス | 日経クロステック(xTECH)
めちゃくちゃ良い
#WIP
Traversableクラスの各メソッドが,「データ構造」とApplicativeやモナドのような「計算を行うコンテナ」の入れ子関係を入れ替える性質を持っている
この性質により,Applicativeやモナドのような計算コンテナを使って処理を行い,最終結果を計算コンテナから取り出すといった処理を簡単に書ける
入り組んだ構造の値を平坦な構造に変換できる
これは例を見ないとわからん #??
https://xtech.nikkei.com/it/article/COLUMN/20120207/380292/?P=2
Traversable則
構造を保つ
code:hs
traverse Identity = Identity -- identity
t . traverse f = traverse (t . f) -- naturality
「舐めてからmap」と「舐めるときにmap」が等しくなる
https://kimiyuki.net/blog/2014/12/21/foldable-and-traversable/
https://xtech.nikkei.com/it/article/COLUMN/20120207/380292/?P=5
https://xtech.nikkei.com/it/article/COLUMN/20120207/380292/?P=6
https://xtech.nikkei.com/it/article/COLUMN/20120207/380292/?P=7
https://kmyk.github.io/blog/blog/2014/12/21/foldable-and-traversable/
https://en.wikibooks.org/wiki/Haskell/Traversable
https://nushio.hateblo.jp/entry/20110504/p1
https://chrispenner.ca/posts/traversal-systems
https://gist.github.com/viercc/9ea0c74b17559773b217e67799f21c39