开发者

prolog: logic programming

开发者 https://www.devze.com 2023-02-10 11:58 出处:网络
How do I write Prolog code that picks out only numbers out of a list containing numbers and letters? For example, if I have [a,b,7,d,3,e,f,5], I want to write code that gives 开发者_JS百科me [7,3,5].

How do I write Prolog code that picks out only numbers out of a list containing numbers and letters? For example, if I have [a,b,7,d,3,e,f,5], I want to write code that gives 开发者_JS百科me [7,3,5]. Thanks in advance.


its easy to put this into a findall:

numList(ListIn, Nums) :-
  findall(H, (member(H, ListIn), number(H)), Nums).

query with:

?- numList([a,b,7,d,3,e,f,5], Nums).
Nums = [7, 3, 5].

prolog's findall is really fantastically useful!


You have to write a function that gives you back a list. There is no such thing as a return statement in Prolog, but you can use parameters to specify out-things as well.

% The second parameter will be our OUT parameter.
% It can be anything that we specify.

% Return an empty list, because our input is empty as well
numFilter([],[]).

% return a list with H and what will come out recursively
numFilter([H|T],[H|T2]) :- number(H), numFilter(T,T2).

% return a list with what will come out recursively. H is not a number
numFilter([H|T],T2) :- not(number(H)), numFilter(T,T2). 

So you specify rules for every kind of input that can happen to you. We have one for an empty list, and we have two for a list that has at least one element. The first element will be checked and we continue with this recursively.

We can call this function with a call like this:

numFilter([a,b,7,d,3,e,f,5],A).

The A is a variable that will be filled in by prolog at runtime. number: 1 is a function that is in the prolog dictionary.

So for these kind of assignments, you need recursion for your lists. Remember that.

0

精彩评论

暂无评论...
验证码 换一张
取 消