(define-struct school (name students))
;; An SchoolChart is a (make-school Str (listof SchoolChart))
;; names are unique
我有学校图表说
(define s-chart (make-school "Tom" (list
(make-school "James" empty)
(make-school "Claire"
(make-school "David" empty)
(make-school "Travis" empty))
(make-school "Timmy" empty))))
这是一般树,比如说我定义了一个函数
(define (find-name name school)) ;;produces true if found/false if not.
我如何进行递归?这个具体案例很好,但每个孩子都可以有无限的孩子吗?我只需要一个提示
答案 0 :(得分:1)
只能有一定数量的孩子 数量是任意的,只受机器内存的限制,但不能无限。
(而你的public ActionResult TransferDevices(IList<XXXViewModel> viewModel)
{
var selected = viewModel.Where(x => x.isSelected).ToList();
IQueryable<Device> devicesQueryable = _db.Devices;
var devices = devicesQueryable.Where(x => selected.Any(y => y.Id == x.Id)).ToList() ;
}
格式不正确,因为“克莱尔”的孩子不是名单。)
递归可以非常简单 这是深度优先搜索:
s-chart
其中(define (find-name name school)
(or (string=? name (school-name school))
(any (lambda (s) (find-name name s)) (school-students school))))
为(any p ls)
当且仅当#t
为(p e)
时,列表#t
的至少一个元素e
。< / p>
现在剩下的就是写ls
...
答案 1 :(得分:0)
以递归方式检查所有项目,如果找到,则将名称添加到循环外的列表中。但是,它需要使用set!
。它使用string-prefix?
代替string=?
用于演示目的(在当前结构中获取更多名称):
(define-struct school (name students))
(define s-chart
(make-school "Tom"
(list
(make-school "James" empty)
(make-school "Claire" (list
(make-school "David" empty)
(make-school "Travis" empty)))
(make-school "Timmy" empty))))
(define (find-name name school)
(define ol '())
(let loop ((s school))
(cond
[(list? s)
(when (not(empty? s))
(begin (loop (first s))
(loop (rest s))))]
[else
(when (string-prefix? (school-name s) name)
(set! ol (cons (school-name s) ol)))
(loop (school-students s))
]))
ol
)
(find-name "T" s-chart)
输出:
'("Timmy" "Travis" "Tom")