Scheme language: merge two numbers

99封情书 提交于 2019-12-07 09:44:23

问题


How can I merge two integers from a list into one? (in Scheme) Example:
'(11 223) -> 11223


回答1:


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:

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



回答2:


This is my original answer from Jan 25 '12 at 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! ; 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)))))

(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. Thank you again blubberdiblub for an explanation of what the poster probably meant, I had missed it.




回答3:


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:

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

etc.



来源:https://stackoverflow.com/questions/8954994/scheme-language-merge-two-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!