Haskell function from (a -> [b]) -> [a -> b]

后端 未结 5 1984
有刺的猬
有刺的猬 2021-01-12 14:06

I have a function seperateFuncs such that

seperateFuncs :: [a -> b] -> (a -> [b])
seperateFuncs xs = \\x -> map ($ x) xs
         


        
5条回答
  •  执念已碎
    2021-01-12 14:41

    You can generalize seperateFuncs to Applicative (or Monad) pretty cleanly:

    seperateFuncs :: (Applicative f) => f (a -> b) -> (a -> f b)
    seperateFuncs f x = f <*> pure x
    

    Written in point-free style, you have seperateFuncs = ((. pure) . (<*>)), so you basically want unap . (. extract), giving the following definition if you write it in pointful style:

    joinFuncs :: (Unapplicative f) => (a -> f b) -> f (a -> b)
    joinFuncs f = unap f (\ g -> f (extract g))
    

    Here I define Unapplictaive as:

    class Functor f => Unapplicactive f where
        extract  :: f a -> a
        unap     :: (f a -> f b) -> f (a -> b)
    

    To get the definitions given by leftaroundabout, you could give the following instances:

    instance Unapplicative [] where
        extract = head
        unap f = [\a -> f [a] !! i | i <- [0..]]
    
    instance Unapplicative ((->) c) where
        extract f = f undefined
        unap f = \x y -> f (const y) x
    

    I think it's hard to come up with a "useful" function f :: (f a -> f b) -> f (a -> b) for any f that isn't like (->).

提交回复
热议问题