我正在计算列表中的实例数...
count(_,[],N,N).
count(Elem,[Elem|List],N,M) :- !, N1 is N+1, count(Elem,List,N1,M).
count(Elem,[_|List],N,M) :- count(Elem,List,N,M).
Run Code Online (Sandbox Code Playgroud)
所以,我在prolog中写了两个方法,第一个工作(上面),但我很想知道为什么第二个没有(或者更确切地说,会给我多个答案 - 只有第一个是正确的)为什么是这个?
非常感谢
count(Z,X,R) :- count2(Z,X,R,0).
count2(W,[H|T],L,A):- (W == H), Lnew is A+1, count2(W,T,L,Lnew).
count2(W,[H|T],L,A):- count2(W,T,L,A).
count2(W,[],A,A).
Run Code Online (Sandbox Code Playgroud) 我试图让我的手臂围绕一些基本的序幕,但有点挣扎.具体来说 - 我试图通过项目列表并将其逐项复制到新列表中.我可以让它扭转,但我发现它没有倒转就踩到了它.
我一直在尝试以下 -
copy(L,R) :- accCp(L,R).
accCp([],R).
accCp([H|T],R) :- accCp(T,H).
Run Code Online (Sandbox Code Playgroud)
当我对此进行追踪时 - 我可以看到正在复制的各个项目,但它们会"丢失",并且不会形成一个增长的列表(在R,正如我希望的那样).我怎么能这样呢?
非常感谢
我很想知道为什么以下内容会在g ++中引发错误(无法在没有对象的情况下调用成员函数).我想一个解决方法是将B类变量作为A中的静态变量 - 但我很想知道为什么,当有一个A的子类C的实例创建时,这仍然会引发错误 - 非常感谢!
#include <iostream>
#include <cstring>
using namespace std;
class B {
public:
double var;
public:
friend class A;
B() : var(1) { };
void set(double new_rate);
};
class A {
protected:
B main_B;
public:
virtual void set_rate(double new_rate) { cout << "test";
//B.set(new_rate);
}
};
class C : public A {
};
/*
void B::set(double new_rate) {
var = new_rate;
cout << "worked " <<current_rate <<endl;
}
*/
int main() {
C test_C;
A::set_rate ( …Run Code Online (Sandbox Code Playgroud) 所以,这个想法是写一个递归函数,比较两个字符串,看看字符串'prefix'是否包含在字符串'other'中,不使用任何标准字符串函数,并使用指针算法.以下是我想出的.我认为它有效,但很奇怪 - 这是多么优雅,1-10级,你会做的任何明显的时髦动作呢?
谢谢.
bool is_prefixR(char* prefix, char* other) {
static int prePos = 0,othPos = 0;
// static int othPos = 0;
bool test;
test = ( *(prefix+prePos) == *(other+othPos)); //checks to see if same
if (!*(prefix+prePos)) { return 1; } //end of recursion
if (!*(other+othPos)) { return 0; }
if (!test) {
othPos++; //move othPos pointer by 1
prePos = 0; //reset the prefix position
return(is_prefixR(prefix, other)); //lets try again
} else { //chars are the same
othPos++; …Run Code Online (Sandbox Code Playgroud) 对于某些函数我想在函数中创建一个字符串的副本,然后操纵它 - 由于一些奇怪的原因,我不能strcpy工作(给我一个分段错误) - 我也尝试将arg作为字符串传递,这也不起作用(g ++抛出一个错误,说它期望一个char*)
#include <iostream>
#include <cstring>
using namespace std;
void copy_string(char* stri);
int main ()
{
copy_string("sample string");
return 0;
}
void copy_string(char* stri) {
char* stri_copy;
strcpy(stri_copy, stri);
cout << "String: " << stri_copy;
}
Run Code Online (Sandbox Code Playgroud)
我不确定我明白为什么会这样.
所以我的两个问题是:
谢谢!