在 Prolog 中将数字拆分为数字列表 [英] Split a number into a list of digits in Prolog

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

问题描述

我在尝试使用 Prolog 将数字拆分为列表时遇到了麻烦,例如123456 变为 [1,2,3,4,5,6].

I've been having trouble trying to split numbers into lists using Prolog, e.g. 123456 becomes [1,2,3,4,5,6].

你能帮我弄清楚怎么做吗?

Can you please help me work out how to do this?

推荐答案

可用的内置函数是 ISO 标准:

the builtins available are ISO standard:

?- number_codes(123456,X),format('~s',[X]).
123456
X = [49, 50, 51, 52, 53, 54].

?- number_chars(123456,X),format('~s',[X]).
123456
X = ['1', '2', '3', '4', '5', '6'].

我还为我的解释器开发了一些非常旧代码.:= 必须重命名为 is 才能与标准 Prologs 一起运行.但是你最好从上面的内置函数中得到服务......

I also have some very old code I developed for my interpreter. := must be renamed is to run with standard Prologs. But then you are best served from above builtins...

itoa(N, S) :-
    N < 0, !,
    NN := 0 - N,
    iptoa(NN, SR, _),
    reverse(SR, SN),
    append("-", SN, S).
itoa(N, S) :-
    iptoa(N, SR, _),
    reverse(SR, S).

iptoa(V, [C], 1) :-
    V < 10, !,
    C := V + 48.
iptoa(V, [C|S], Y) :-
    M := V / 10,
    iptoa(M, S, X),
    Y := X * 10,
    C := V - M * 10 + 48.

编辑此处获取号码所需的额外调用:

edit here the additional call required to get numbers:

?- number_codes(123456,X), maplist(plus(48),Y,X).
X = [49, 50, 51, 52, 53, 54],
Y = [1, 2, 3, 4, 5, 6].

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

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