全局存储Scheme中的值
我需要执行一系列数学运算。函数的输入为n。
前两个运算是求和。使用 n.结果需要存储为变量以便在以后的函数中使用。
前任。
main func(n)
func1 (n)
returns a1
func2 (n)
returns b1
func4
uses b1 to compute c1
etc....
我已经创建了所有分开的函数,但需要使用一个仅接受 n 的主函数,以及一种全局存储变量以便在以后的函数中使用的方法(无需更改它们)。这是前两个函数。
(define (main n)
(define (a1func n)
(let* ((a1 0))
(let* ((i (- n 1)))
(if (= n 1) 0
(+(/ 1 i) (a1func(- n 1)))))))
(define (a2func n)
(let ((a2 0))
(let ((i (- n 1)))
(if (= n 1) 0
(+(/ 1 (expt i 2)) (a2func(- n 1)))))))
(define b1
(if (= n 1) 0
(/(+ n 1)(* 3(- n 1)))))
(define b2
(if (= n 1) 0
(/(* 2 (+ n 3 (expt n 2))) (*(- n 1)(* 9 n)))))
(define c1 (- b1 (/ 1 a1)))
(define c2 (+ (- b2 (/ (+ n 2) (* a1 n))) (/ a2 (expt a1 2))))
(define e1 (/ c1 a1))
(define e2 (/ c2 (+ (expt a1 2) a2)))
(list e1 e2))
I have a series of mathmetical operations I need to perform. The input of the function is n.
the first two operations are summations. using n. The result needs stored as a variable to be used in later functions.
ex.
main func(n)
func1 (n)
returns a1
func2 (n)
returns b1
func4
uses b1 to compute c1
etc....
I've created all the functions sepearted but need to use a main function that merely takes in n, and a way to store the variables globally for use in later functions (without changing them). these are the first 2 functions.
(define (main n)
(define (a1func n)
(let* ((a1 0))
(let* ((i (- n 1)))
(if (= n 1) 0
(+(/ 1 i) (a1func(- n 1)))))))
(define (a2func n)
(let ((a2 0))
(let ((i (- n 1)))
(if (= n 1) 0
(+(/ 1 (expt i 2)) (a2func(- n 1)))))))
(define b1
(if (= n 1) 0
(/(+ n 1)(* 3(- n 1)))))
(define b2
(if (= n 1) 0
(/(* 2 (+ n 3 (expt n 2))) (*(- n 1)(* 9 n)))))
(define c1 (- b1 (/ 1 a1)))
(define c2 (+ (- b2 (/ (+ n 2) (* a1 n))) (/ a2 (expt a1 2))))
(define e1 (/ c1 a1))
(define e2 (/ c2 (+ (expt a1 2) a2)))
(list e1 e2))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
函数式编程不同于命令式编程。方案是一种函数式语言。不要使用绑定变量作为内存位置。但如果你需要像内存位置这样的东西,那么使用向量。
如果您想在另一个函数中使用变量的值,请将其作为参数传递给该函数:
Functional programming is different from imperative programming. Scheme is a functional language. Do not use bound variables as memory locations. But if you need something like memory locations then use vector.
If you want to use the value of variable in another functior then pass it to that function as a parameter:
使用另一个函数的输出使一个函数计算结果的惯用方法是组合。在以下示例中,您希望
add2
处理add1
的结果,并通过组合函数来实现:如果您确实想要工作对于全局状态,您可以借助闭包来做到这一点,这样全局名称空间本身就不会被破坏:
The idiomatic way to make a function compute result using the output of another function is composition. In the following example, you want
add2
to work on the result ofadd1
and achieve that by composing the functions:If you really want to work with global state, you can do that with the help of closures so that the global namespace itself is not spoiled: