高阶函数和 id
Higher order functions and id
我似乎无法理解 id
是如何用作某些高阶函数的参数的。我在某处读到它已经习惯了 "leave something alone" 但我似乎无法理解它。
比如liftA2 id
的类型为什么是f (b -> c) -> f b -> f c
?
此外,为什么我不能将 id
传递给 g
for
g :: (Int -> Int -> Int) -> Int -> Int -> Int
?
I've read somewhere that [id
] is used to "leave something alone" but can't seem to get my head around it.
id
用于“留下一些东西”,因为它就是这样做的——也就是说,什么都不做:
id :: x -> x
id x = x
因此,id
通常显示为传递给 higher-order 函数的 do-nothing 占位符。 fmap id foo
实际上并没有改变在 foo
中找到的值(实际上,fmap id = id
,这是第一函子定律),id . f
和 f . id
都是相当于 f
,等等。一个更有趣的例子是 the classic trick of defining foldl
using foldr
,其中 id
被用作用 foldr
.
构建函数的基本情况
For example, why is the type of liftA2 id
f (b -> c) -> f b -> f c
?
liftA2
的类型是:
liftA2 :: (a -> b -> c) -> f a -> f b -> f c
在 liftA2 id
的情况下,我们有...
(a -> (b -> c)) ~ (x -> x)
...等等...
a ~ x
(b -> c) ~ x
...因此...
liftA2 id :: f (b -> c) -> f b -> f c
(你可能知道,liftA2 id = (<*>)
。如果你把它写成 liftA2 ($)
,发生的事情可能会更明显,($) :: (a -> b) -> (a -> b)
只是一个专门的 id
.)
Also, why can't I pass id
to g
for
g :: (Int -> Int -> Int) -> Int -> Int -> Int
因为那时你必须统一...
(Int -> (Int -> Int)) ~ (x -> x)
... 这是不可能的,因为 x
不能同时是 Int
和 Int -> Int
.
我似乎无法理解 id
是如何用作某些高阶函数的参数的。我在某处读到它已经习惯了 "leave something alone" 但我似乎无法理解它。
比如liftA2 id
的类型为什么是f (b -> c) -> f b -> f c
?
此外,为什么我不能将 id
传递给 g
for
g :: (Int -> Int -> Int) -> Int -> Int -> Int
?
I've read somewhere that [
id
] is used to "leave something alone" but can't seem to get my head around it.
id
用于“留下一些东西”,因为它就是这样做的——也就是说,什么都不做:
id :: x -> x
id x = x
因此,id
通常显示为传递给 higher-order 函数的 do-nothing 占位符。 fmap id foo
实际上并没有改变在 foo
中找到的值(实际上,fmap id = id
,这是第一函子定律),id . f
和 f . id
都是相当于 f
,等等。一个更有趣的例子是 the classic trick of defining foldl
using foldr
,其中 id
被用作用 foldr
.
For example, why is the type of
liftA2 id
f (b -> c) -> f b -> f c
?
liftA2
的类型是:
liftA2 :: (a -> b -> c) -> f a -> f b -> f c
在 liftA2 id
的情况下,我们有...
(a -> (b -> c)) ~ (x -> x)
...等等...
a ~ x
(b -> c) ~ x
...因此...
liftA2 id :: f (b -> c) -> f b -> f c
(你可能知道,liftA2 id = (<*>)
。如果你把它写成 liftA2 ($)
,发生的事情可能会更明显,($) :: (a -> b) -> (a -> b)
只是一个专门的 id
.)
Also, why can't I pass
id
tog
forg :: (Int -> Int -> Int) -> Int -> Int -> Int
因为那时你必须统一...
(Int -> (Int -> Int)) ~ (x -> x)
... 这是不可能的,因为 x
不能同时是 Int
和 Int -> Int
.