簡體   English   中英

這是Haskell高階函數嗎?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM