这是Haskell的高阶函数吗?

use*_*071 0 haskell higher-order-functions

我想知道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)
Run Code Online (Sandbox Code Playgroud)

dav*_*420 5

这些函数都不是高阶函数,因为这些函数都不将函数作为参数.

shift的参数是n(a 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
Run Code Online (Sandbox Code Playgroud)

或者,也许更有用:

anotherHigherShift :: (Int -> Int) -> Char -> Char
anotherHigherShift f c = inttochar (f (chartoInt c))

shift n = anotherHigherShift (+n)   -- same as your original shift
Run Code Online (Sandbox Code Playgroud)

您可以阅读类型签名anotherHigherShift的话说,

  • 这是一个功能
  • 其第一个参数是一个函数(该函数接受Int并返回一个Int)
  • 其第二个参数是 Char
  • 并返回一个 Char

(+n)是简写\m -> m + n.