Haskell 什么是符号<$&燃气轮机;及<*&燃气轮机;你是说哈斯克尔?

Haskell 什么是符号<$&燃气轮机;及<*&燃气轮机;你是说哈斯克尔?,haskell,Haskell,符号和是什么意思 此外,我还找到了一些有关的信息,这些运算符在控件.Applicative中定义。操作符只是fmap的中缀版本: f <$> a = fmap f a 使用,您可以更轻松地搜索Haskell函数和运算符 Applicativetypeclass介于Functor和Monad之间: class Functor where ... class Functor f => Applicative f where ... class Applicative m =&

符号
是什么意思


此外,我还找到了一些有关

的信息,这些运算符在
控件.Applicative
中定义。
操作符只是
fmap
的中缀版本:

f <$> a = fmap f a
使用,您可以更轻松地搜索Haskell函数和运算符

Applicative
typeclass介于
Functor
Monad
之间:

class Functor where ...

class Functor f => Applicative f where ...

class Applicative m => Monad m where ...
(注意,这是
Applicative
Monad
之间的关系,仅在最近发布的GHC 7.10中强制执行)

应用程序是遵循特定规则的结构。它比函子强,但比单子弱。具体来说,函子只能对结构中的值应用单参数函数,返回包含新值但不包含新形状的新结构。典型的例子是
fmap(+1)[1,2,3]==[2,3,4]
,输入列表的长度始终与输出列表的长度相同。使用Applications,您可以跨多个结构应用多参数纯函数:

> (+) <$> [1, 2, 3] <*> [10, 20]
[11, 21, 12, 22, 13, 23]
(+)[1,2,3][10,20] [11, 21, 12, 22, 13, 23] 输出列表的长度(“形状”)取决于输入列表的长度。但是,需要注意的是,输出列表的长度并不取决于列表中的值。这是单子添加到此层次结构中的能力:

> print $ do a <- [1, 2, 3]; b <- replicate a 10; return (a + b)
[11, 12, 12, 13, 13, 13]
是fmap的同义词,
是中缀运算符。它通常用于应用函子的上下文中

import Control.Applicative ((<$>)

-- (<$>), fmap :: Functor f => (a -> b) -> f a -> f b

example1 :: (Int -> Int) -> Maybe Int -> Maybe Int
example1 f g = f <$> g  -- f `fmap` (Just x) = Just (f x)
                        -- f `fmap` Nothing  = Nothing
import Control.Applicative()
--(),fmap::函子f=>(a->b)->f a->f b
例1::(Int->Int)->可能Int->可能Int
示例1fg=fg--f`fmap`(正好x)=正好(fx)
--f`fmap`Nothing=Nothing
另一方面,
在函子上下文中有一个函数,并且希望将该函数应用于另一个函子上下文中的某个值时非常有用,例如:

example2:: Maybe (Int -> Int) -> Maybe Int -> Maybe Int
example2 f g = f <*> g -- (Just f) <*> (Just x) = Just ( f x)
                       -- Nothing  <*> (Just x ) = Nothing
                       -- (Just f) <*> Nothing   = Nothing
                       -- Nothing <*>  Nothing   = Nothing
example2::Maybe(Int->Int)->Maybe Int->Maybe Int
例2fg=fg——(正好f)(正好x)=正好(fx)
--没什么(只是x)=没什么
--(只是f)无=无
--没什么
它可以被描绘成应用函数的操作符,同时考虑应用函数的上下文


这些操作符将值和函数提升到执行操作的函子的上下文。

Google通常不是搜索符号的合适引擎(不过,我现在无法让它给我任何结果),尤其是Haskell,因为它有自己的优秀,这会让你马上找到它的定义。听说过hoogle吗?@AJFarmar,是的,现在我知道这项服务了。这应该是
[1,2,3]
在最后一个例子中?@SebastianRedl它应该是
1
而不是
a
,谢谢你指出它。@Denis没问题!我会说我花了很长时间研究应用程序,它们是介于函子和单子之间的一个奇怪的区域,有一些细微差别,这些差别不是很明显。在这一点上,我将d鼓励您尝试通过流行的parsec或attoparsec库了解更多有关应用程序的信息,这两种库都严重依赖于应用程序运算符。虽然知道如何使用它们很重要,但在很多情况下,没有它们肯定是可以过得去的。不过,大多数人更喜欢
而不是
fmap
,因此,希望看到很多。可能值得一提的是,
(+)[1,2,3]
实际上是
[(1+),(2+),(3+)
example2:: Maybe (Int -> Int) -> Maybe Int -> Maybe Int
example2 f g = f <*> g -- (Just f) <*> (Just x) = Just ( f x)
                       -- Nothing  <*> (Just x ) = Nothing
                       -- (Just f) <*> Nothing   = Nothing
                       -- Nothing <*>  Nothing   = Nothing