Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
正在寻找一些问题来提高我对可折叠和仿函数的了解,但似乎不太了解如何使用可折叠和仿函数创建 toList 函数
到目前为止,我不确定是否需要在这里创建自己的可折叠实例
我想使用下面的类型定义显式创建 toList
instance Foldable [] where fold = undefined toList :: (Functor c, Foldable c) => c a -> [a] toList f = undefined
对我必须做的任何帮助和解释表示赞赏
要编写toList,您实际上只需要Foldable约束。实际上,您只需要foldr. 关键的见解是以下定律。什么时候xs是列表,
toList
Foldable
foldr
xs
foldr (:) [] xs = xs
但类型foldr (:) []是
foldr (:) []
Foldable t => t a -> [a]
这意味着它将anyFoldable变成一个列表。果然,这是一个可接受的定义toList:
toList :: Foldable t => t a -> [a] toList = foldr (:) []