且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Scheme 中创建一个集合的分区

更新时间:2023-02-14 20:02:46

Issues

您的代码存在一些问题.

Issues

There are some issues in your code.

这将创建一个列表:

(list '(7 5))  ; => ((7 5))

其中的 cdr 始终是一个空列表.

A cdr of that is always an empty list.

(cdr (list '(7 5)))  ; => ()

以这种方式创建单个列表:

A single list is created in this way:

(define l (list 7 5))

或者这样:

(define l '(7 5))

第二个

您在 Scheme 中使用括号进行应用.这:

Second

You use parenthesis in Scheme for application. This:

(#t)

表示执行函数#t".但是 #t 不是函数,它是一个布尔值.并且不能执行布尔值.

means "execute the function #t". But #t is not a function, it is a Boolean value. And Boolean values can not be executed.

你可以直接返回一个布尔值

Your can return a Boolean value directly

#t

或者你可以返回一个返回值的函数

or you can return a function returning the value

(lambda () #t)

但是你不能执行true.

but you can not execute true.

同样的问题.代码如下:

Same problem in or. The following code:

(or ((two-subsets (cdr l) (+ s1 1) s2 (+ l1 1) l2)
     (two-subsets (cdr l) s1 (+s2 1) l1 (+ l2 1))))

表示:two-subsets 必须返回一个函数.第一个 two-subsets 调用返回的函数与第二个 two-subsets 调用返回的函数一起执行.并且将单个结果值传递给 or.这可能不是您想要的.

means: two-subsets must return a function. The function returned by the first two-subsets call gets executed with the function returned by the second two-subsets call. And the single result value gets passed to or. This is probably not what you want.

如果要or两次调用two-subsets的两个返回值,必须去掉两个括号.

If you want to or the two return values of the two calls to two-subsets, you have to remove two parenthesis.

(or (two-subsets (cdr l) (+ s1 1) s2 (+ l1 1) l2)
    (two-subsets (cdr l) s1 (+s2 1) l1 (+ l2 1)))

提示

  • 定义一个与您的结束条件相匹配的函数.该函数接受两个列表参数并检查它们是否具有相同的大小(length)和总和(您可以使用 apply 将列表传递给 +代码>).剧透
  • 编写一个遍历所有可能子集的函数.并为每个组合调用您的匹配函数.迭代是通过 Scheme 中的递归完成的.要么定义一个调用自身的函数,要么使用一个命名的 let.
  • Hints

    • Define a function which matches your end condition. The function takes two list arguments and checks, if they have the same size (length) and sum (you can use apply to pass a list to +). Spoiler
    • Write a function which iterates through all possible subsets. And call your match function with each combination. Iteration is done by recursion in Scheme. Either define a function, which calls itself or use a named let.