IN Racket Define a function that takes two arguments

落爺英雄遲暮 提交于 2019-12-13 08:57:33

问题


I need some one can explain for me to how to do this please

Define a function that takes two arguments, a list of numbers and a single number (the threshold). It should return a new list that has the same numbers as the input list, but with all elements greater than the threshold number removed. You may not use the built-in filter function as a helper function. Your implementation must be recursive.

INPUT: A list of numbers and a single atomic number.

OUTPUT: A new list of numbers that contains only the numbers from the original list that are strictly “less than” (<), i.e. below the threshold number.

Example:
> (upper-threshold '(3 6.2 7 2 9 5.3 1) 6)
'(3 2 5.3 1)
> (upper-threshold '(1 2 3 4 5) 4)
'(1 2 3)
> (upper-threshold '(4 8 5 6 7) 6.1)
'(4 5 6)
> (upper-threshold '(8 3 5 7) 2)
'()

This what I have so far but I receve error

(define (upper-threshold pred lst)
  (cond [(empty? lst) empty]
        [(pred (first lst))
         (cons (first lst) (upper-threshold pred (rest lst)))]
        [else (upper-threshold pred (rest lst))]))

; (threshold (lambda (x) (> x 5)) '(1 6 7))

回答1:


I don't quite understand your code. However, you might be looking for something like this:

(define (upper-threshold lst theshold)
  (cond
    ((null? lst) '())
    ((< (car lst) theshold)
     (cons (car lst)
           (upper-threshold (cdr lst) theshold)))
    (else (upper-threshold (cdr lst) theshold))))

If your purpose is to implement the standard function filter, perhaps you should write the code some another way.




回答2:


Your implementation doesn't have the same arguments as your assignment.

You need something that compares the first element with the second argument so see it its larger or not, then either (cons (car lst) (upper-treshold (cdr lst) streshold)) to include the first element in the result or (upper-treshold (cdr lst) treshold) to not include it.

(define (upper-threshold lst treshold)
  (cond [(empty? lst) empty]
        [(> (car lst) treshold)
         (cons (first lst) (upper-threshold (rest lst) treshold))]
        [else (upper-threshold (rest lst) treshold)]))



回答3:


It appears that you've taken a filter function and renamed it as upper-threshold. It's true that these two are related. I would suggest trying to build upper-threshold from scratch, using the design recipe:

http://www.ccs.neu.edu/home/matthias/HtDP2e/

When you get confused, refer to existing functions that you have, including the definition of filter that you have here. Your example may be slightly harder to understand because it uses lambda.



来源:https://stackoverflow.com/questions/45026005/in-racket-define-a-function-that-takes-two-arguments

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