在scheme中结合count和flatten函数 [英] Combining count and flatten functions in scheme

查看:58
本文介绍了在scheme中结合count和flatten函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这两个单独工作的函数.我正在尝试编写一个函数来完成这两个任务,但我不断收到汽车错误.有关解决此问题的最佳方法的任何指导?

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))))  

我尝试过这样的事情,我对函数式编程还很陌生,所以我仍然试图将我的想法围绕在它上面说问题出在数字之后?(汽车 lst)

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))))))))

推荐答案

正如我在评论中提到的,我认为将所有内容都放在一个函数中并不是一个好主意.无论如何,你有点在正确的轨道上,但我们必须记住,如果我们要返回一个数字作为最终结果,那么我们的基本情况应该反映这一点并返回一个数字(不是空列表),并且组合步骤应该add 数字,而不是append 数字.这就是我的意思:

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)))

但我宁愿这样做:

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

我们甚至可以仅使用内置程序编写惯用的解决方案,检查解释器的文档,但在 Racket 中我们可以这样做:

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

这篇关于在scheme中结合count和flatten函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆