You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Racket自定义my-subset?函数实现求助:无法完成非子集场景的代码编写

Fixing Your my-subset? Function in Racket

Hey there! Let's walk through fixing your my-subset? function—you're already off to a great start with your member helper, we just need to tweak the logic in the main function to make it work correctly.

First, let's break down what's off in your current my-subset? code:

  • You're wrapping lst2 in (list lst2) when calling member, which means you're checking if the first element of lst1 exists in a list that contains only lst2 itself (not the elements of lst2). That's not what we want—we need to check against lst2 directly.
  • Your cond branch doesn't handle the case where an element from lst1 is not in lst2. Right now, you just return #t if the first element matches, but we need to immediately return #f if any element is missing, and only recurse if the current element is present.

Corrected Code

Your member helper is actually perfect—no changes needed there! Here's the fixed my-subset? function:

(define (member x lst) 
  (cond [(empty? lst) #f] 
        [(equal? x (first lst)) #t] 
        [else (member x (rest lst))])) 

(define (my-subset? lst1 lst2) 
  (cond 
    [(empty? lst1) #t]  ; Empty list is a subset of every list—correct as is
    [(not (member (first lst1) lst2)) #f]  ; If current element isn't in lst2, not a subset
    [else (my-subset? (rest lst1) lst2)]))  ; If current element is present, check the rest of lst1

How It Works

Let's walk through the logic step by step:

  1. Base Case: If lst1 is empty, return #t (per your problem's requirement that empty lists are subsets of all lists).
  2. Failure Case: If the first element of lst1 isn't found in lst2 (using your member function), we immediately return #f—since even one missing element means lst1 can't be a subset.
  3. Recursive Case: If the first element is in lst2, we recursively check if the rest of lst1 is a subset of lst2. This repeats until we either hit the base case (all elements checked, return #t) or the failure case (return #f).

Test Examples to Verify

Try running these to make sure it works:

  • (my-subset? '() '(1 2 3)) → #t (empty list subset)
  • (my-subset? '(1 2) '(1 2 3)) → #t
  • (my-subset? '(1 4) '(1 2 3)) → #f (4 isn't in lst2)
  • (my-subset? '(3 2) '(1 2 3)) → #t (order doesn't matter for subsets)

内容的提问来源于stack exchange,提问作者SaSi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 15:27:49