序言类型错误 [英] Prolog Type Error

查看:61
本文介绍了序言类型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一种对列表执行交换"的序言算法.

I'm working on a prolog algorithm that will perform a "swap" on a list.

示例:

输入:[1,2,3,4] -> 输出:[3,4,1,2]输入:[1,2,3,4,5] -> 输出:[4,5,3,1,2]

Input: [1,2,3,4] -> Output: [3,4,1,2] Input: [1,2,3,4,5] -> Output: [4,5,3,1,2]

列表的前半部分和后半部分交换位置,如果有奇数,则中心元素保留其位置.我想出了一个算法,但出现错误:

The first half and second half of the list swap places, if there is an odd number then the center element retains it's position. I have come up with an algorithm, but I am getting an error:

?- swap([1,2,3,4],L).
ERROR: length/2: Type error: `integer' expected, found `round(4/2)'

我的代码如下:

swap(L, S) :-
    length(L, Length),
    reverse(L, L2),
    mixing(L, Length, A),
    trim(L2, Length/2 , B),
    append(A,B,S).

trim(L,N,S) :-
    length(P,N),
    append(P,S,L).

mixing(L, Length, A) :-
    (  mod(Length, 2) == 0
    -> trim(L, round(Length/2), A)
    ;  trim(L, round(Length/2), A)
    ).

问题是,在混合"中,当我调用 trim (L, round(Length/2), A) 时,类型不是整数?我知道 Length/2 不是整数(很可能是浮点数),我认为 round 相当于 integer(expr) ,它将数据类型舍入并将数据类型转换为整数.我也尝试用 truncate(expr) 和 integer(expr) 替换 round,但我收到了相同的错误.有人可以解释我做错了什么吗?

The problem is that in 'mixing' when I call trim (L, round(Length/2), A) the type is not integer? I understand that Length/2 is not an integer (most likely a float) and I thought round was equivalent to integer(expr) which rounds and transforms the data type to an integer. I also tried replacing round with the truncate(expr) and integer(expr), but I was receiving the same errors. Can someone explain what I'm doing wrong?

推荐答案

round 不是函数,而是谓词.我没有看过其余的代码,但那行应该是

round is not a function, it's a predicate. I haven't looked at the rest of the code, but that line should be

round(Length/2, R), trim(L, R, A)

顺便说一句,你想多了.

BTW, you're overthinking it.

swap([], []).
swap([X], [X]).
swap([X, Y | A], [Y, X | B]) :- swap(A, B).

这篇关于序言类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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