我一直试图用F#编写一个程序,该程序需要两个值(一个元组):一个数字和一个字符串。根据字符串是告诉程序进行加还是乘运算,它会将输入数字与从1到该数字的所有整数(即1..n)相加或相乘。
这是代码
let addormult (n:int, what:string) =
if what = "multiply" then
let rec product n =
if n<1 then 0
else n*product(n-1)
printfn "%A" product
elif what = "sum" then
let rec sum =
if n<1 then 0
else n + sum(n-1)
printfn "%A" sum
但是,每次我尝试运行此功能时,都会收到错误消息
"This value is not a function and cannot be applied."
那我在做什么错?
最佳答案
在这部分代码中:
let rec sum =
if n<1 then 0
else n + sum(n-1)
sum
被定义为一个值,因为它不包含任何参数。第三行尝试将其作为函数调用(sum(n-1)
),这是不可能的,因为它不是函数。向函数添加参数,例如
let rec sum x =
if x<1 then 0
else x + sum(x-1)
在这里,我冒昧地将函数主体中的
n
替换为x
,尽管我不知道这是否是您想要的。它可以编译。
关于f# - 此值不是函数,不能应用F#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38882240/