Combining count and flatten functions in scheme

房东的猫 提交于 2019-12-25 04:09:22

问题


So i have these two functions that work fine alone. I am trying to write one function to accomplish both but i keep getting a car error. Any guidance on the best way to solve this?

(define (countNumbers lst)
  (cond
 ((null? lst) 0)
 ((number? (car lst))(+ 1 (countNumbers (cdr lst))))
 (else (countNumbers (cdr lst)))))

(define (flatten x)
  (cond ((null? x) '())
        ((pair? x) (append (flatten (car x)) (flatten (cdr x))))
        (else (list x))))  

I tried something like this im rather new to functional programming in general so im still trying to wrap my mind around it it says the problem is after number?(car lst)

(define (flatten lst)
  (cond ((null? lst) '())
        ((pair? lst) (append (flatten (car lst)) (flatten (cdr lst))))
        (else (list(cond
 ((null? lst) 0)
 ((number? (car lst))(+ 1 (flatten (cdr lst))))
 (else (flatten (cdr lst))))))))

回答1:


As I mentioned in my comment, I don't think it's a good idea to stick everything in a single function. Anyway, you were kinda on the right track, but we have to remember that if we're going to return a number as the final result, then our base case should reflect this and also return a number (not an empty list), and the combining step should add numbers, not append them. This is what I mean:

(define (count-flatten lst)
  (cond ((null? lst) 0)
        ((pair? lst)
         (+ (count-flatten (car lst))
            (count-flatten (cdr lst))))
        ((number? lst) 1)
        (else 0)))

But I'd rather do this:

(define (count-flatten lst)
  (countNumbers (flatten lst)))

We can even write an idiomatic solution using only built-in procedures, check your interpreter's documentation, but in Racket we can do this:

(define (count-flatten lst)
  (count number? (flatten lst)))

Anyway, it works as expected:

(count-flatten '(1 x (x 2) x (3 (4 x (5) 6) 7)))
=> 7


来源:https://stackoverflow.com/questions/28311776/combining-count-and-flatten-functions-in-scheme

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