方案:返回一个只包含 lst 的第一个元素的 lst [英] scheme: return a lst that only contains the first element of the lst

查看:41
本文介绍了方案:返回一个只包含 lst 的第一个元素的 lst的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题来了:

编写一个函数(first-n-elements lst n),它返回一个只包含lst的前n个元素的列表.例如,(first-n-elements '(1 2 3 4 5 6) 3) 应该返回 '(1 2 3).您的函数应该处理 n 大于列表长度的情况(在这种情况下它将返回整个列表),并且 n 为 0(应该返回'()).

Write a function (first-n-elements lst n), which returns a list containing only the first n elements of lst. For example, (first-n-elements '(1 2 3 4 5 6) 3) should return '(1 2 3). Your function should handle the case where n is greater than the length of the list (in which case it would return the entire list), and where n is 0 (should return '()).

我的回答是:

(define (first-n-elements lst n)
  (cond((null? lst) '())    
       ((= n 0) lst))   
       ((> n 0) (cons (+ (car lst) 1) (first-n-elements) (cdr lst) (- n 1))))

我知道错了,请帮忙

推荐答案

部分问题说如果 n 为 0,它应该返回 '().但是当 n 为 0 时,你的函数会做什么?

Part of the question says that if n is 0, it should return '(). But what does your function do when n is 0?

另外,想想这里的递归情况(> n 0).您当前正在返回四个参数的 cons:

Also, think about the recursive case here (> n 0). You're currently returning the cons of four arguments:

  • (+ (car lst) 1)
  • (first-n-elements)
  • (cdr lst)
  • (- n 1)

但是 cons 只接受两个参数.你有所有的部分,但它们并没有完全正确地组合在一起.你想缺点一起做什么?

But cons only takes two arguments. You have all the parts there, but they're not quite put together right. What do you want to be consing together?

另外:你为什么要在 (car lst) 上加 1?如果 lst 中包含数字以外的其他内容,这将不起作用.

Also: why are you adding 1 to (car lst)? That's not going to work if lst has something other than numbers in it.

这篇关于方案:返回一个只包含 lst 的第一个元素的 lst的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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