我想知道 shift 是否是高阶函数。
chartoInt :: Char -> Int
chartoInt c = ord c
Inttochar :: Int -> Char
Inttochar n = chr n
shift :: Int -> Char -> Char
shift n c = Inttochar (chartoInt c + n)
我想知道 shift 是否是高阶函数。
chartoInt :: Char -> Int
chartoInt c = ord c
Inttochar :: Int -> Char
Inttochar n = chr n
shift :: Int -> Char -> Char
shift n c = Inttochar (chartoInt c + n)
这些函数都不是高阶函数,因为这些函数都没有将函数作为参数。
shift的参数是n(an Int) 和c(a Char):函数都不是。
(另外:Inttochar应该是inttochar:Haskell 中的函数名不能以大写字母开头。)
这是一个看起来像您的高阶函数shift:
higherShift :: (Int -> Char) -> Int -> Char -> Char
higherShift f n c = f (chartoInt c + n)
shift = higherShift inttochar -- same as your original shift
或者,也许更有用:
anotherHigherShift :: (Int -> Int) -> Char -> Char
anotherHigherShift f c = inttochar (f (chartoInt c))
shift n = anotherHigherShift (+n) -- same as your original shift
您可以阅读类型签名anotherHigherShift作为说
Int并返回一个Int)CharChar(+n)是 的简写\m -> m + n。
这是。
shift 是一个高阶函数。
shift :: Int -> (Char -> Char) -- The long prototype.
它获取Int和返回函数获取Char和返回Char。
PS你应该写inttochar。
有一个非正式的规则:看看函数的类型。如果它包含(有必要[1])大括号,那么它是一个更高阶的函数。
[1] 意味着省略它们会改变类型。
现在从这个角度来看第一个答案的函数类型和函数。这很简单。