在 lets-lens 教程中,您如何重构对遍历的调用以实现结束?
In the lets-lens tutorial, how do you refactor out the call to traverse in order to implement over?
在the exercises中我实现了fmapT
:
-- Let's remind ourselves of Traversable, noting Foldable and Functor.
--
-- class (Foldable t, Functor t) => Traversable t where
-- traverse ::
-- Applicative f =>
-- (a -> f b)
-- -> t a
-- -> f (t b)
-- | Observe that @fmap@ can be recovered from @traverse@ using @Identity@.
--
-- /Reminder:/ fmap :: Functor t => (a -> b) -> t a -> t b
fmapT ::
Traversable t =>
(a -> b)
-> t a
-> t b
fmapT =
error "todo: fmapT"
现在我该如何实施 over
?
-- | Let's refactor out the call to @traverse@ as an argument to @fmapT@.
over ::
((a -> Identity b) -> s -> Identity t)
-> (a -> b)
-> s
-> t
over = error "undefined"
您可以使用 traverse
实现 fmapT
作为:
fmapT f s = runIdentity (traverse (Identity . f) s)
现在下一个练习是通过在定义中提供 traverse
作为参数而不是 hard-coding 来重构此函数。如果您选择 Identity
作为应用类型构造函数,那么 traverse
的类型是:
(Traversable t) => (a -> Identity b) -> t a -> Identity (t b)
如果您将此作为参数提供给 fmapT
,您最终会得到类似 over
:
的结果
over' :: Traversable t => ((a -> Identity b) -> t a -> Identity (t b)) -> (a -> b) -> t a -> t b
over' l f s = runIdentity (l (Identity . f) s)
因为 Traversable
约束存在于 traverse
中,over'
不需要 over'
,它具有练习中给出的更通用的 over
类型,即 [=26] =]
over :: ((a -> Identity b) -> (s -> Identity t)) -> (a -> b) -> s -> t
和
over' = over traverse
在the exercises中我实现了fmapT
:
-- Let's remind ourselves of Traversable, noting Foldable and Functor.
--
-- class (Foldable t, Functor t) => Traversable t where
-- traverse ::
-- Applicative f =>
-- (a -> f b)
-- -> t a
-- -> f (t b)
-- | Observe that @fmap@ can be recovered from @traverse@ using @Identity@.
--
-- /Reminder:/ fmap :: Functor t => (a -> b) -> t a -> t b
fmapT ::
Traversable t =>
(a -> b)
-> t a
-> t b
fmapT =
error "todo: fmapT"
现在我该如何实施 over
?
-- | Let's refactor out the call to @traverse@ as an argument to @fmapT@.
over ::
((a -> Identity b) -> s -> Identity t)
-> (a -> b)
-> s
-> t
over = error "undefined"
您可以使用 traverse
实现 fmapT
作为:
fmapT f s = runIdentity (traverse (Identity . f) s)
现在下一个练习是通过在定义中提供 traverse
作为参数而不是 hard-coding 来重构此函数。如果您选择 Identity
作为应用类型构造函数,那么 traverse
的类型是:
(Traversable t) => (a -> Identity b) -> t a -> Identity (t b)
如果您将此作为参数提供给 fmapT
,您最终会得到类似 over
:
over' :: Traversable t => ((a -> Identity b) -> t a -> Identity (t b)) -> (a -> b) -> t a -> t b
over' l f s = runIdentity (l (Identity . f) s)
因为 Traversable
约束存在于 traverse
中,over'
不需要 over'
,它具有练习中给出的更通用的 over
类型,即 [=26] =]
over :: ((a -> Identity b) -> (s -> Identity t)) -> (a -> b) -> s -> t
和
over' = over traverse