简体   繁体   English

方案语言:合并两个数字

[英]Scheme language: merge two numbers

How can I merge two integers from a list into one? 如何将列表中的两个整数合并为一个? (in Scheme) Example: (在Scheme中)示例:
'(11 223) -> 11223 '(11 223) - > 11223

Assuming that the list has exactly two elements, and that both are numbers: 假设列表中只有两个元素,并且两个元素都是数字:

(define (merge-numbers lst)
  (let ((1st (number->string (first  lst)))
        (2nd (number->string (second lst))))
    (string->number (string-append 1st 2nd))))

It works as expected: 它按预期工作:

(merge-numbers '(11 223))
> 11223

Alternatively, without using a let : 或者,不使用let

(define (merge-numbers lst)
  (string->number
   (string-append
    (number->string (first  lst))
    (number->string (second lst)))))

This is my original answer from Jan 25 '12 at 3:05. 这是我在12月25日3:05的原始答案。 It only handles the given test. 它只处理给定的测试。 It was a mindless answer, sorry. 抱歉,这是一个无意识的回答。

(define (merge ls) 11223)    
(merge '(11 223))

This is my new answer that handles all cases when passed a list of numbers. 这是我的新答案,它在传递数字列表时处理所有情况。 Thank you blubberdiblub for the pointer! 谢谢你blubberdiblub的指针! ; ; list of zero or more strings -> string (define (merge-numbers ns) (if (null? ns) "" (let ((first-n (number->string (car ns))) (rest-ns (cdr ns))) (string-append first-n (merge-numbers rest-ns))))) 零个或多个字符串的列表 - > string(define(merge-numbers ns)(if(null?ns)“”(let((first-n(number-> string(car ns)))(rest-ns(cdr) ns)))(string-append first-n(merge-numbers rest-ns)))))

(merge-numbers '(11 223))
(merge-numbers '())
(merge-numbers '(1))
(merge-numbers '(1 2))
(merge-numbers '(1 2 3))
(merge-numbers '(1 2 3 4))
(merge-numbers '(1 2 3 4 5))

"11223"
""
"1"
"12"
"123"
"1234"
"12345"

Since the original question probably meant that the result should be a number, and this results in a string, then string->number needs to be used to get the final answer. 由于原始问题可能意味着结果应该是一个数字,并且这会产生一个字符串,因此需要使用string- string->number来获得最终答案。 Thank you again blubberdiblub for an explanation of what the poster probably meant, I had missed it. 再次感谢blubberdiblub解释海报可能意味着什么,我错过了它。

There are many ways to write this procedure, depending on what you plan for it. 编写此过程有很多方法,具体取决于您的计划。 For example, if the list might contain more than two numbers (in the future?) then you can write it as follows: 例如,如果列表可能包含两个以上的数字(将来?),那么您可以按如下方式编写它:

(define merge-numbers
  (lambda (s)
    (string->number
      (apply string-append
        (map number->string s)))))

So now you can type: 所以你现在可以输入:

> (merge-numbers '(4 9 66 33 555 1))
4966335551

If there's a real reason why you want the number two, then I think the use of the procedure format would be more readable: 如果你想要第二个的真正原因,那么我认为使用过程format会更具可读性:

(define merge-two-numbers
  (lambda (s)
    (string->number
      (format "~a~a"
        (car s)
        (cadr s)))))

etc. 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM