Haskell 哈斯克尔基本函数定义
我正在学习haskell,但我并不真正理解函数定义,例如:Haskell 哈斯克尔基本函数定义,haskell,Haskell,我正在学习haskell,但我并不真正理解函数定义,例如: module TestModule where iter :: Int -> (a -> a) -> (a -> a) iter n f | n>0 = f . iter (n-1) f | otherwise = id iter_2 n f = foldr (.) id (replicate n f) 我想给这个函数什么?我已经通过控制台加载了这个函数,但并不真正理解
module TestModule where
iter :: Int -> (a -> a) -> (a -> a)
iter n f
| n>0 = f . iter (n-1) f
| otherwise = id
iter_2 n f = foldr (.) id (replicate n f)
我想给这个函数什么?我已经通过控制台加载了这个函数,但并不真正理解如何使用它
我的问题是如何通过控制台使用此功能。如“iter 5?”将函数类型解读为
iter :: Int -> (a -> a) -> a -> a
^^^ ^^^^^^^^ ^ ^
arg arg arg result
这意味着如果您提供一个Int
、一个(a->a)
函数和一个a
,它将返回另一个a
。这里a
代表任何类型。比如说
iter 4 (+1) 0
将是4
,即在0
上执行(+1)
四次。您需要给它一个函数,更具体地说,一个内函数(将任何类型映射到自身)。比如说,
*Main> iter 3 sqrt 256
2.0
当然,这也可以是一个自定义函数,如
*Main> let f x = x+2
*Main> iter 3 f 7
13
甚至是在调用中定义的匿名调用:
*Main> iter 3 (\str -> "("++str++")") "..."
"(((...)))"
. “通过控制台使用此功能”是什么意思?你说你已经加载了。非常感谢!!!你能举个例子:“交错::流a->流a->流a”?