来自(a - > [b])的Haskell函数 - > [a - > b] [英] Haskell function from (a -> [b]) -> [a -> b]
问题描述
我有一个函数 seperateFuncs
,使得
seperateFuncs :: [a -> b] -> (a -> [b])
seperateFuncs xs = \x -> map ($ x) xs
我想知道是否存在逆向,即是否有函数
I was wondering whether the converse existed, i.e. is there a function
joinFuncs :: (a -> [b]) -> [a -> b]
我认为不是(主要是因为列表不是固定长度),但也许我会证明是错的。
问题是有一些数据类型 f
,它有一个函数::(a - > fb) - > f(a - > b)?
I think not (mainly because lists are not fixed length), but perhaps I'll be proved wrong.
The question then is there some datatype f
which has a function :: (a -> f b) -> f (a -> b)?
推荐答案
您可以将 seperateFuncs
归纳为 Applicative
$(code> Monad )很干净:
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
使用无点式书写,您有 seperateFuncs =( 。)(<*>))
,所以你基本上需要 unap。 (。extract)
,给出下面的定义,如果你用有意义的风格写出它:
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))
这里我将 Unapplictaive
定义为:
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
我认为很难想出一个有用的函数 f ::(fa - > fb) - >对于不同于
( - >)$的任何
c $ c>。 f
,f(a - > b)
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 (->)
.
这篇关于来自(a - > [b])的Haskell函数 - > [a - > b]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!