gpt4 book ai didi

functional-programming - 在一行中打印答案、 "should be"和所需的答案 [方案(初级学生语言)]

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:45 26 4
gpt4 key购买 nike

我目前正在解决Ex。 3.3.1 其中:

Exercise 3.3.1. The United States uses the English system of (length) measurements. The rest of the world uses the metric system. So, people who travel abroad and companies that trade with foreign partners often need to convert English measurements to metric ones and vice versa.

Here is a table that shows the six major units of length measurements of the English system:12

English metric 1 inch = 2.54 cm 1 foot = 12 in. 1 yard = 3 ft. 1 rod = 5(1/2) yd. 1 furlong = 40 rd. 1 mile = 8 fl. Develop the functions inches->cm, feet->inches, yards->feet, rods->yards, furlongs->rods, and miles->furlongs.

Then develop the functions feet->cm, yards->cm, rods->inches, and miles->feet.

Hint: Reuse functions as much as possible. Use variable definitions to specify constants.

;; Contract: inches->cm

;; Purpose: to convert inches to centimeters

;; Examples: (inches->cm 22/7) should be 7.9828514

;; Definition: [refines the header]
(define (inches->cm in)
(* in 2.54))

;; Tests
(inches->cm 22/7) "should be" 7.98287514

当我运行程序时,它是这样运行的:

7.98285714
"should be"
7.98285714

我一直在考虑的一个可能的缺陷是,如果我的代码具有多个功能和多个设计方案,如果我的程序像这样运行,我将更难阅读:

7.98285714
"should be"
7.98285714
-11.9928
"should be"
-11.9928
9.4247736
"should be"
9.4247736

要弄清楚哪个是哪个会花费我很多时间。有没有办法让程序像下面的代码一样运行?

7.98285714 "should be" 7.98285714

-11.9928 "should be" -11.9928

9.4247736 "should be" 9.4247736

我对这种“函数式编程”范式和编程语言还是陌生的,我不知道是否有类似 printf() 的东西和/或 \n就像在 C 中一样。但是请耐心等待。

最佳答案

如果您的问题是结果以单独的行打印,试试这个 - 它适用于 Beginning Student Language:

(define (print actual expected)
(string-append
(number->string (exact->inexact actual))
" should be "
(number->string (exact->inexact expected))))

(print (inches->cm 22/7) 7.98287514)
=> "3.142857142857143 should be 7.98287514"

如果您不局限于初学者的语言,这将是 Racket 中更简单的替代方案:

(printf "~a should be ~a~n" (inches->cm 22/7) 7.98287514)

或者更好的是,使用 check-expect或其他一些单元测试框架,有更适合这项工作的工具。不要重新发明轮子!

关于functional-programming - 在一行中打印答案、 "should be"和所需的答案 [方案(初级学生语言)],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25089439/

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