我的名字是Michael Boutros,我现在是高中的高年级学生.明年我将参加滑铁卢大学,并作为他们CS课程的入门读物,我一直在做一些任务.他们使用的语言是Scheme,我一直在学习它.我来自
PHP和Ruby背景,所以我担心从这些语言中学到的一些习惯被错误地应用到我正在使用的方案中.以下是作业中的问题(顺便提一下在线提供):
Write a function called sub-time that consumes a string start-time representing a time, and a
natural number mins which represents the number of minutes before. The function produces a
string representing mins minutes before the given time start-time.The string consumed will be formatted as follows: a two digit number, followed by “ hours ”,
followed by a two digit number, followed by “ minutes”. The time consumed is in 24-hour
format. If the number of hours or minutes is less than 10, then the number will include a leading 0.
The string produced must be in exactly the following format: a number, followed by “ hours ”,
followed by a number, followed by “ minutes”. Note that the string produced does not have a
leading 0 before numbers less than 10. It is possible that the time produced could represent a time
on a previous day.For example,
• (sub-time “03 hours 15 minutes” 0) produces
“3 hours 15 minutes”,
• (sub-time “13 hours 05 minutes” 845) produces
“23 hours 0 minutes”, and
• (sub-time “13 hours 05 minutes” 2881) produced
“13 hours 4 minutes”The built-in Scheme functions string->number and number->string may be useful.
It is very important that you produce the string exactly as described, otherwise the autotests will fail. In particular, all characters must be in lower case and there must be single
spaces between all parts of the string.Do not use any cond expressions in your solution.
(老实说,直到现在我才注意到最后一行,我的解决方案确实使用了条件表达式.有没有办法避免它们?)
这是我的解决方案:
;; Assignment 1 Question 4
(define (convert-to-string hours minutes)
(string-append (number->string hours) " hours " (number->string minutes) " minutes"))
(define (subtract_hours start_hours sub_hours minutes)
(let ((hours (- start_hours (modulo sub_hours 24))))
(if (< hours 0)
(convert-to-string (+ 24 hours) minutes)
(convert-to-string hours minutes))))
(define (subtract_minutes start_hours start_minutes sub_hours sub_minutes)
(let ((minutes (- start_minutes sub_minutes)))
(if (< minutes 0)
(subtract_hours start_hours (+ 1 sub_hours) (+ 60 minutes))
(subtract_hours start_hours sub_hours minutes))))
(define (sub-time start-time mins)
(let ((start_hours (string->number (substring start-time 0 2)))
(start_minutes (string->number (substring start-time 9 11)))
(sub_hours (quotient mins 60))
(sub_minutes (modulo mins 60)))
(subtract_minutes start_hours start_minutes sub_hours sub_minutes)))
我对Scheme非常不熟悉,虽然我的解决方案有效(来自我的有限测试),但我想知道一些经验丰富的老兵不得不说.谢谢你的时间!
最佳答案 是的,您可以在没有任何条件的情况下编写此代码.考虑将小时分钟转换为分钟数,然后进行减法,然后将结果转换回小时分钟.