gpt4 book ai didi

haskell ·帕斯卡三角形

转载 作者:行者123 更新时间:2023-12-02 19:48:04 24 4
gpt4 key购买 nike

我必须创建一个递归函数,它接受两个数字(n 和 k)并返回它们的二项式系数。

我必须使用 pascal::Int -> Int -> Int

老实说我不明白哪里出了问题,感谢您的帮助!

pascal :: Int -> Int -> Int
pascal n k
| k == 0 = 1
| n == n = 1
| k > n = 0
| otherwise = pascal(n-1)(k-1) + pascal(n-1) + k

以下错误是:

main.hs:7:40: error:
• Couldn't match expected type ‘Int’ with actual type ‘Int -> Int’
• Probable cause: ‘pascal’ is applied to too few arguments
In the second argument of ‘(+)’, namely ‘pascal (n - 1)’
In the first argument of ‘(+)’, namely
‘pascal (n - 1) (k - 1) + pascal (n - 1)’
In the expression: pascal (n - 1) (k - 1) + pascal (n - 1) + k
|
7 | | otherwise = pascal(n-1)(k-1) + pascal(n-1) + k
| ^^^^^^^^^^^
<interactive>:3:1: error:
• Variable not in scope: main
• Perhaps you meant ‘min’ (imported from Prelude)

最佳答案

正如异常(exception)情况所示,pascal (n-1) 没有多大意义,因为它是一个函数Int -> Int,所以你不能添加 pascal (n-1) (k-1)pascal (n-1) 在一起。

因此您需要传递一个额外的参数。例如:

pascal :: Int -> Int -> Int
pascal _ 0 = 1
pascal n k
| k == n = 1
| k > n = 0
| otherwise = pascal (n-1) (k-1) + <b>pascal (n-1) k</b>

请注意,条件n == n始终为真,您可能想说n == k

关于 haskell ·帕斯卡三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58879008/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com