简体   繁体   English

标准Haskell函数::(a - >可能是a) - > a - > [a]

[英]Standard Haskell function :: (a -> Maybe a) -> a -> [a]

I have a function defined 我有一个功能定义

maybeToList :: (a -> Maybe a) -> a -> [a]
maybeToList f x = x : maybe [] (maybeToList f) (f x)

This function seems so obvious that I can't believe it is not standard. 这个功能看起来很明显,我不敢相信它不标准。 Is it defined in some module (I already checked Data.Maybe)? 它是否在某个模块中定义(我已经检查过Data.Maybe)?

Your function isn't in the standard libraries because it's a specialized form of one that is : 你的功能是不是在标准库,因为它是一种特殊形式的一个是

unfoldr      :: (b -> Maybe (a, b)) -> b -> [a]
unfoldr f b  =
  case f b of
   Just (a,new_b) -> a : unfoldr f new_b
   Nothing        -> []

That said, the case where the list elements are the same as the sequence of seed values is common, and it's clumsy to write in terms of just unfoldr and other standard functions, so I'm not sure why it's not in the standard libraries as well. 也就是说,列表元素与种子值序列相同的情况很常见,并且根据unfoldr和其他标准函数来编写是笨拙的,所以我不确定它为什么不在标准库中好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM