使用 Prolog 的 collat​​z-list 实现 [英] collatz-list implementation using Prolog

查看:59
本文介绍了使用 Prolog 的 collat​​z-list 实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Prolog 中创建一个名为 collat​​z_list 的函数.这个函数有两个参数,第一个是数字,第二个是列表.这个列表将是我这个函数的输出.所以,这是我的功能:

I am trying to create a function called collatz_list in Prolog. This function takes two arguments, the first one is a number and the second in a list. This list will be my output of this function. So, here's my function:

collatz_list(1,[1]).
collatz_list(N,[H|T]) :-
   N > 1,
   N mod 2 =:= 0,
   collatz_list(N, [H|T]).  
collatz_list(N,[H|T]) :-
   N > 1,
   N mod 2 =:= 1,
   N is N*3 +1,
   collatz_list(N,[H|T]). 

我正在努力创建输出列表.任何人都可以帮助我吗?

I am struggling with creating the output list. Can anyone help me on that?

谢谢.

推荐答案

假设你想写一个带有参数 (int, list)collat​​z_list/2 谓词,其中list 是从 int 开始并最终以 1 结尾的 collat​​z 序列(我们希望如此!到目前为止这是一个未解决的问题);您只需要以声明方式对递归定义进行编码.

Assuming you want to write a collatz_list/2 predicate with parameters (int, list), where list is the collatz sequence starting with int and eventually ending with 1 (we hope so! It's an open problem so far); you just have to code the recursive definition in the declarative way.

这是我的尝试:

/* if N = 1, we just stop */
collatz_list(1, []).

/* case 1: N even
   we place N / 2 in the head of the list
   the tail is the collatz sequence starting from N / 2 */
collatz_list(N, [H|T]) :-
    0 is N mod 2,
    H is N / 2, 
    collatz_list(H, T), !. 

/* case 2: N is odd
   we place 3N + 1 in the head of the list
   the tail is the collatz sequence starting from 3N + 1 */
collatz_list(N, [H|T]) :-
    H is 3 * N + 1, 
    collatz_list(H, T). 

修改后的版本,包括起始编号

让我们测试一下:

full_list(N, [N|T]) :-
    collatz_list(N, T).

collatz_list(1, []).

collatz_list(N, [H|T]) :-
    0 is N mod 2,
    H is N / 2, 
    collatz_list(H, T), !. 

collatz_list(N, [H|T]) :-
    H is 3 * N + 1, 
    collatz_list(H, T). 

?- full_list(27, L).
L = [27, 82, 41, 124, 62, 31, 94, 47, 142|...].

这篇关于使用 Prolog 的 collat​​z-list 实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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