Haskell程式查詢正數的階乘
本教程討論了在Haskell程式語言中編寫查詢正數階乘的程式。
在本教程中,我們將看到
使用遞迴函式查詢正數階乘的程式。
使用內建函式product查詢正數階乘的程式。
演算法步驟
輸入或初始化一個變數來儲存一個正整數。
實現查詢數字階乘的程式邏輯。
列印結果階乘。
方法:使用遞迴函式查詢正數的階乘
示例
使用內建函式product查詢正數階乘的程式
-- function declaration factorial :: Int->Int -- function definition factorial n = product [1..n] main :: IO() main = do -- initializing variable n let n = 5 -- printing the resulting factorial print ("The factorial of a number " ++ show n ++ " is:") print (factorial n)
輸出
"The factorial of a number 5 is:" 120
描述
我們聲明瞭一個名為factorial的函式,它接受一個整數引數並返回一個整數。在其函式定義中,該函式接受一個整數n作為引數。該函式使用雙點運算子呼叫一個名為product的函式,該函式的引數列表是從1到n的整數。
product函式接受一個數字列表作為引數並返回它們的乘積。這裡從1到n的所有數字的乘積就是n的階乘。該函式返回product函式的輸出。
在主函式中,變數n被初始化為數字值5。factorial函式被呼叫,引數為數字n,並使用print函式列印返回的輸出。
注意 - show函式接受一個數字作為引數並返回該數字的解析字串。“++”是Haskell中連線字串的運算子。
方法2:使用內建函式Product查詢正數的階乘
示例
使用遞迴函式查詢正數階乘的程式
-- function declaration factorial :: Int->Int -- function definition --base case factorial 0 = 1 factorial n = (n) * factorial (n-1) main :: IO() main = do -- initializing variable n let n = 5 -- printing the resulting factorial print ("The factorial of a number " ++ show n ++ " is:") print (factorial n)
輸出
"The factorial of a number 5 is:" 120
描述
聲明瞭一個名為factorial的函式,它接受一個整數引數並返回一個整數。在其函式定義中,它接受一個整數引數n並返回數字n與自身對引數n-1的遞迴呼叫的乘積。
遞迴呼叫被呼叫,直到函式達到基本情況,其中引數為0。在基本情況下,函式返回1。此函式計算數字的階乘。
在主函式中,變數n被初始化為數字值5。factorial函式被呼叫,引數為數字n,並使用print函式列印返回的輸出。
結論
在本教程中,我們討論了兩種在Haskell程式語言中實現查詢正數階乘的程式的方法。
廣告