Function 使用嵌套函数查找数的乘积
我需要做一个函数,给定自然数n,计算乘积 n以下的数字中不能被 2或3我对如何使用嵌套函数来解决这个问题感到困惑(对sml来说也是新的)Function 使用嵌套函数查找数的乘积,function,functional-programming,nested,sml,Function,Functional Programming,Nested,Sml,我需要做一个函数,给定自然数n,计算乘积 n以下的数字中不能被 2或3我对如何使用嵌套函数来解决这个问题感到困惑(对sml来说也是新的) fun countdown(x : int) = if x=0 then [] else x :: countdown(x-1) fun check(countdown : int list) = if null countdown then 0 else 问题本身(某个类中练习的一部分?)并不清楚我们应该如
fun countdown(x : int) =
if x=0
then []
else x :: countdown(x-1)
fun check(countdown : int list) =
if null countdown
then 0
else
问题本身(某个类中练习的一部分?)并不清楚我们应该如何使用嵌套函数,因为有一些方法可以编写不嵌套的函数,例如
fun p1 n =
if n = 1 then 1 else
let val m = n - 1
in (if m mod 2 = 0 orelse m mod 3 = 0 then 1 else m) * p1 m
end
还有很多方法可以用嵌套函数编写它,比如
fun p2 n =
if n = 1 then 1 else
let val m = n - 1
fun check m = (m mod 2 = 0 orelse m mod 3 = 0)
in (if check m then 1 else m) * p2 m
end
或
或者像@coder前面的回答一样,只举几个例子。其中,
p3
有些特殊,因为内部函数loop
有一个“自由变量”n
,它指的是外部p3的一个参数,问题本身并不清楚(某类练习的一部分?)我们应该如何使用嵌套函数,因为有一些方法可以在不嵌套的情况下编写函数,例如
fun p1 n =
if n = 1 then 1 else
let val m = n - 1
in (if m mod 2 = 0 orelse m mod 3 = 0 then 1 else m) * p1 m
end
还有很多方法可以用嵌套函数编写它,比如
fun p2 n =
if n = 1 then 1 else
let val m = n - 1
fun check m = (m mod 2 = 0 orelse m mod 3 = 0)
in (if check m then 1 else m) * p2 m
end
或
或者像@coder前面的回答一样,只举几个例子。其中,p3
有点特殊,因为内部函数循环
有一个“自由变量”n
,它是指使用标准库的外部p3
的一个参数,该函数产生数字[1;n-1]
删除可被2或3整除的数字的函数
val filter23 = List.filter (fn i => i mod 2 <> 0 andalso i mod 3 <> 0)
把它们粘在一起
val f = product o filter23 o below
这将生成一个列表,过滤并折叠它。这会浪费更多的内存。做@FPstudent和@coder所做的事情,生成数字,并立即将其作为最终产品的一部分,或者如果它们可以被2或3整除,则将其丢弃,这样会更有效。除此之外,你还可以做两件事
使函数尾部递归,因此它使用更少的堆栈空间
将迭代/折叠概括为通用模式
比如说,
fun folditer f e i j =
if i < j
then folditer f (f (i, e)) (i+1) j
else e
fun accept i = i mod 2 <> 0 andalso i mod 3 <> 0
val f = folditer (fn (i, acc) => if accept i then i*acc else acc) 1 1
fun folditer f e i j=
如果我如果接受i,则i*acc否则acc)1
这类似于。使用标准库,这是一个生成数字[1;n-1]的函数
删除可被2或3整除的数字的函数
val filter23 = List.filter (fn i => i mod 2 <> 0 andalso i mod 3 <> 0)
把它们粘在一起
val f = product o filter23 o below
这将生成一个列表,过滤并折叠它。这会浪费更多的内存。做@FPstudent和@coder所做的事情,生成数字,并立即将其作为最终产品的一部分,或者如果它们可以被2或3整除,则将其丢弃,这样会更有效。除此之外,你还可以做两件事
使函数尾部递归,因此它使用更少的堆栈空间
将迭代/折叠概括为通用模式
比如说,
fun folditer f e i j =
if i < j
then folditer f (f (i, e)) (i+1) j
else e
fun accept i = i mod 2 <> 0 andalso i mod 3 <> 0
val f = folditer (fn (i, acc) => if accept i then i*acc else acc) 1 1
fun folditer f e i j=
如果我如果接受i,则i*acc否则acc)1
这类似于