[英]Is this a Haskell higher order function?
我想知道移位是否是高階函數。
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
(一個Int
)和c
(一個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
) Char
Char
(+n)
是\\m -> m + n
簡寫。
它是。
移位是高階函數。
shift :: Int -> (Char -> Char) -- The long prototype.
它獲取Int
並返回函數,獲取Char
並返回Char
。
PS您應該寫inttochar
。
有一個非正式的規則:看一下函數的類型。 如果包含(必要[1])大括號,則它是一個更高階的函數。
[1]省略它們會改變類型。
現在,從這種角度來看,從第一個答案看一下您的函數類型和函數。 這很簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.