仅查找列表中的数字 [英] Find only numbers in list

查看:50
本文介绍了仅查找列表中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要写一个规则,只查找列表 M 中的数字并只输出列表 O 中的数字.

I need to write a rule, what finds only numbers in list M and outputs only the numbers in list O.

查询看起来像:find(M, O)

我自己无法解决,希望有人能帮助我.

I can't figure it out on my own and hope someone can help me.

推荐答案

这是一个经典的 Prolog"方法:

Here is a "classical Prolog" way to do it:

find([], []).
find([H|T], [H|NewT]) :-
    number(H),
    find(T, NewT).
find([H|T], NewT) :-
    \+ number(H),
    find(T, NewT).

有 3 个子句.

1st 表示对于一个空列表,结果是一个空列表.

1st says that for an empty list the result is an empty list.

2nd 说:如果输入列表的第一个元素 (head, H) 是一个数字,则将其保留在输出中,其余的输出(新尾,NewT) 被 find 应用于输入列表的其余部分(tail, T).

2nd says: if the first element (head, H) of the input list is a number, keep it in the output, and the rest of the output (new tail, NewT) is find applied to the rest of the input list (tail, T).

第三个子句在结构上与第二个类似,但表示如果不是数字就不要保持头脑.

3rd clause is structurally similar to the second, but says not to keep head if it's not a number.

这篇关于仅查找列表中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆