搜索方案中的嵌套列表以找到一个数字 [英] search through nested list in scheme to find a number
问题描述
如何搜索嵌套列表以找到某个数字?
How would I search through the nested list to find a certain number?
例如列表为:
((1 2) (2 3) (3 4) (3 5) (4 5))
我正在寻找 1.
预期输出:
(1 2)
因为 1 在子列表中 (1 2).
since 1 is in the sub list (1 2).
推荐答案
首先创建函数来扁平化列表.像这样:
First of all create function to flatten list. Something like this:
> (flatten '((8) 4 ((7 4) 5) ((())) (((6))) 7 2 ()))
(8 4 7 4 5 6 7 2)
然后在普通列表中搜索您的号码.
And then search your number in the ordinary list.
这个问题看起来像作业,所以尝试自己开发这个功能,如果你不能做到 - 在这里发布你的代码,我会尽力帮助你.
This quesion looks like the homework so try to develop this function on your own and if you can not do it - post your code here and I'll try to help you.
更新
好的.据我了解,我们需要创建一个函数来获取对列表并返回另一个对列表,其中对的第一个元素等于某个数字.
Ok. As I understand we need to create function which get the list of pairs and return another list of pairs, where first element of pair equal some number.
例如:
(define data '((1 2)(2 3)(3 4)(3 5)(4 5)))
(solution data 3)
-> '((3 4) (3 5))
(define data '((1 2)(2 3)(3 4)(3 5)(4 5)))
(solution data 1)
-> '((1 2))
换句话说,我们需要根据某些条件过滤我们的对列表.在 Scheme 中有一个 过滤列表的功能.它需要一个列表来过滤和函数来决定 - 在结果列表中包含或不包含列表元素.
In the other words we need to filter our list of pairs by some condition. In the Scheme there is a function to filter list. It takes a list to filter and function to decide - to include or not the element of list in the result list.
所以我们需要创建这样的函数:
So we need to create such function:
(define (check-pair num p)
(cond
[(= (first p) num) #t]
[else #f]))
此函数获取一对(列表元素),编号并决定 - 将此对包含或不包含到结果列表中.这个函数有2个参数,但是filter函数需要只有一个参数的函数,所以我们这样重写我们的函数:
This function get a pair (element of list), number and decide - incude or not this pair to result list. This function have 2 parameters, but the filter function require the function with only one parameter, so we rewrite our function such way:
(define (check-pair num)
(lambda (p)
(cond
[(= (first p) num) #t]
[else #f])))
我创建了产生另一个函数的函数.这是柯里化.
I have created function wich produce another function. It is currying.
所以,我们必须创建我们的解决方案:
So, we have all to create our solution:
(define (check-pair num)
(lambda (p)
(cond
[(= (first p) num) #t]
[else #f])))
(define (solution list num)
(local
((define check-pair-by-num (check-pair num)))
(filter check-pair-by-num list)))
(define data '((1 2)(2 3)(3 4)(3 5)(4 5)))
(solution data 1)
这篇关于搜索方案中的嵌套列表以找到一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!