开发者

best way to write a-> ..->[a] recursive functions in haskell

开发者 https://www.devze.com 2023-01-03 07:07 出处:网络
So I keep having this small problem where I have something like func :: a -> b -> [a]-- # or basically any a-> ...-> [a] where ... is any types->

So I keep having this small problem where I have something like

func :: a -> b -> [a]  -- # or basically any a-> ...-> [a] where ... is any types  ->
func x y = func' [x] y -- '# as long as they are used to generate a list of [a] from x

func' :: [a] -> b -> [a] 
func' = undefined -- # situation dependant generates a list from
               开发者_运维百科   -- # each element and returns it as one long list

should I keep it like this?

should I use func' hidden by a where?

should I only use the [a] -> b -> [a] version and leave the responsibility of passing [variable] to the callee?

I might well need to compose these functions and might want to mess around with the order so I'm leaning towards option 3. What do you think?


It looks like you are trying to reinvent concatMap:

concatMap :: (a -> [b]) -> [a] -> [b]
concatMap f = concat . map f

So the "map" bit takes each element of the input list applies "f" to it. "f" takes a single "a" and returns a "[b]". These individual lists are then concatenated into a single list.


As Paul noted, func' can be replaced with concatMap and func.

And func itself reminds me of unfoldr from Data.List:

unfoldr :: (b -> Maybe (a, b)) -> b -> [a]

It is used to generate a list of a from b.

By the way, func and func' are unfortunate names for such functions.

0

精彩评论

暂无评论...
验证码 换一张
取 消