我去了几个Haskell学习示例,但我无法弄清楚如何在Haskell中编写用户定义的高阶函数
如果我们将一个参数作为函数如何定义函数id的类型?
答案 0 :(得分:10)
让我们使用函数map
作为一个简单的例子。 map
接受一个函数和一个列表,并将该函数应用于列表的所有元素。如果你写了map
的签名,它就像这样运行:
首先,你需要一个功能。任何函数都可以,所以第一个参数的类型是a -> b
。然后,您需要一个输入值列表。由于列表元素的类型必须适合函数的输入,因此列表的类型为[a]
。对于输出:当应用于a -> b
类型的值时,函数a
的结果是什么?是的,它是b
。所以结果类型是[b]
。组装在一起,我们的函数类型如下:
map :: (a -> b) -> [a] -> [b]
并且定义如下:
map f [] = []
map f (x:xs) = f x : map f xs
这是否有助于您理解高阶函数的概念?
答案 1 :(得分:7)
暂时不要关心类型。询问编译器,它会告诉你类型。通过一些练习,您几乎可以看到类型和编译器[grin]。
这里我们定义了两个非常简单的高阶函数twice
和compose
。第一个接受一个函数和一个参数,并将一个应用于另一个,两次。第二个接受两个函数和一个参数,并在链中将两个函数应用于它。
$ ghci
GHCi, version 6.12.1: http://www.haskell.org/ghc/ :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.
Prelude> let twice f x = f (f x)
Prelude> :t twice
twice :: (t -> t) -> t -> t
Prelude> let compose f g x = f (g x)
Prelude> :t compose
compose :: (t1 -> t2) -> (t -> t1) -> t -> t2
Prelude>
您可以看到twice
获得两个类型(t->t)
类型为t
的参数,并返回类型为t
的结果。 t
是任何类型(但在所有4次出现中都相同)。
您可以尝试在某些常规函数上使用这些高阶函数。
Prelude> let times3 x = x * 3
Prelude> let times5 x = x * 5
Prelude> twice times3 2
18
Prelude> twice times5 2
50
Prelude> compose times3 times5 2
30
Prelude>
回答一些时髦的高级内容:
Prelude> (twice twice) times3 2
162
Prelude> twice (twice times3) 2
162
Prelude>
你能理解最后两个例子中发生了什么吗?