如何分别计算Scheme中每个子列表与目标列表的匹配得分
Got it, let's work through this problem together. You need to calculate a match score for each family member by counting how many of their items appear in the target list. Here's a straightforward way to implement this in Scheme:
Step 1: Define Your Inputs
First, let's set up the original family list and target list as you provided:
(define family (list (list 'Daddy 't-shirt 'raincoat 'sunglasses 'pants 'coat 'sneakers) (list 'Mamma 'high-heels 'dress 'pants 'sunglasses 'scarf) (list 'son 'pants 'sunglasses 'sneakers 't-shirt 'jacket) (list 'daughter 'bikini 'Leggings 'sneakers 'blouse 'top))) (define target (list 'sneakers 'dress 'pants 'sunglasses 'scarf))
Step 2: Create a Helper Function to Count Matches
We'll start with a helper function that takes a list of items and the target list, then returns the number of items that are present in the target:
(define (count-matches items target) ; Filter items that exist in the target list, then get the length of that filtered list (length (filter (lambda (item) (member item target)) items)))
filtergoes through each item and keeps only those where(member item target)returns true (meaning the item is in the target list).lengthgives us the count of those matching items, which is our score.
Step 3: Calculate Scores for Each Family Member
Next, we'll write a function that processes the entire family list, calculating the score for each member:
(define (family-scores family target) (map (lambda (member) ; Split each member's list into their name (first element) and their items (rest of the list) (let ((name (car member)) (items (cdr member))) ; Return a list pairing the name with their calculated score (list name (count-matches items target)))) family))
mapapplies our lambda function to every sublist in thefamilylist.- For each member, we use
letto split out their name and items, then compute their score and pair it with their name.
Step 4: Run the Code
When you call (family-scores family target), you'll get the following result:
((Daddy 3) (Mamma 4) (son 3) (daughter 1))
Let's verify that:
- Daddy has
sunglasses,pants,sneakers→ 3 points - Mamma has
dress,pants,sunglasses,scarf→ 4 points - Son has
pants,sunglasses,sneakers→ 3 points - Daughter only has
sneakers→ 1 point
That lines up perfectly with what we need!
内容的提问来源于stack exchange,提问作者user9736725

