在许多过程语言(例如 python)中,我可以“解包”一个列表并将其用作函数的参数。例如...
def print_sum(a, b, c):
sum = a + b + c
print("The sum is %d" % sum)
print_sum(*[5, 2, 1])
Run Code Online (Sandbox Code Playgroud)
此代码将打印:“ The sum is 8”
有没有办法在 Prolog 中复制这种参数解包行为?
例如,我想在将列表变量传递给call之前解压缩它。
我可以写一个这样的谓词吗?
assert_true(Predicate, with_args([Input])) :-
call(Predicate, Input).
% Where `Input` is somehow unpacked before being passed into `call`.
Run Code Online (Sandbox Code Playgroud)
...然后我可以查询
?- assert_true(reverse, with_args([ [1, 2, 3], [3, 2, 1] ])).
% Should be true, currently fails.
?- assert_true(succ, with_args([ …Run Code Online (Sandbox Code Playgroud) 我正在编写一个prolog程序来检查变量是否是整数.我"返回"结果的方式很奇怪,但我认为回答我的问题并不重要.
我已经写了通过单元测试此行为; 他们来了...
foo_test.pl
:- begin_tests('foo').
:- consult('foo').
test('that_1_is_recognised_as_int') :-
count_ints(1, 1).
test('that_atom_is_not_recognised_as_int') :-
count_ints(arbitrary, 0).
:- end_tests('foo').
:- run_tests.
Run Code Online (Sandbox Code Playgroud)
这是通过这些测试的代码......
foo.pl
count_ints(X, Answer) :-
integer(X),
Answer is 1.
count_ints(X, Answer) :-
\+ integer(X),
Answer is 0.
Run Code Online (Sandbox Code Playgroud)
测试正在通过,这很好,但我在运行它时会收到警告.这是运行测试时的输出...
?- ['foo_test'].
% foo compiled into plunit_foo 0.00 sec, 3 clauses
% PL-Unit: foo
Warning: /home/brandon/projects/sillybin/prolog/foo_test.pl:11:
/home/brandon/projects/sillybin/prolog/foo_test.pl:4:
PL-Unit: Test that_1_is_recognised_as_int: Test succeeded with choicepoint
. done
% All 2 tests passed
% foo_test …Run Code Online (Sandbox Code Playgroud) 通常在使用Ruby进行编程时,我会发现自己正在编写一个小的for循环,并在正文中使用单个语句.例如...
for number in 1..10
puts number
end
Run Code Online (Sandbox Code Playgroud)
在其他语言中C,Java或者Kotlin(例如),我可以在两行中编写相同的代码.例如...
// Kotlin
for (number in 1..10)
println(number)
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,由于缺少花括号而推断出循环体的结尾.
Ruby有没有办法模仿"for loop"的"单一语句"风格?
以下是[我的选项/您的潜在回复],以及我对它们的看法.
你可以附加
; end到身体以在同一条线上结束它.
这是真的,而且非常充足,但我想知道是否有更惯用的方法.
这似乎不必要地挑剔.你为什么要这样做?
你可能会认为我太挑剔了.您也可能认为我想要做的事情是非惯用的(如果这甚至是一个词).我完全理解,但我仍然想知道它是否可行!
这样做可以让我们编写的代码甚至可以更好地阅读.对于程序员来说,可读性至关重要.
在这段代码中:
int length = atoi(argv[1]);
char *tab = malloc(length * sizeof(char));
memset(tab, '-', length);
puts(tab);
Run Code Online (Sandbox Code Playgroud)
无论我传递什么价值argv[1],输出都是正确的.例如,argv[1] = "5"我得到-----(五个连字符).
我想知道puts()当我没有在我的数组的末尾放置'\ 0'时如何找到输入字符串的结尾char.
我是Kotlin的初学者.你如何解释以下代码片段?
fun main(args: Array<String>) {
var k = listOf<Double>(1.2,77.8,6.3,988.88,0.1)
k.forEach(::println)
}
Run Code Online (Sandbox Code Playgroud)
运行正常,并提供列表,但有人可以帮助解释k.forEach(:: println)如何真正起作用?
我必须创建一个名为Myset的类,其中包含IsEmpty(),Insert(Object O)等方法.我想使用Linked对象列表来实现Myset类.但是,由于我是Java的新手,我不得不创建对象本身,即使我不清楚如何开始.我想到了这样的事情:
public class Myset {
LinkedList<Object> LL = new LinkedList<Object>();
}
Run Code Online (Sandbox Code Playgroud)
我还需要编写一个方法:: public Myset Union(Myset a)返回一个集合,它是当前集合与集合a的并集.这可以通过迭代a来完成,如果a中特定索引处的元素不包含在LL中,那么我们将该元素添加到LL.但是我如何在Java代码中编写它?
PS:这是一个赋值问题,我们不允许使用Sets实现.