Prolog 累加器反转 [英] Prolog accumulator reversing

查看:42
本文介绍了Prolog 累加器反转的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,我提出的每个 Prolog 问题的答案最终都会被颠倒答案列表.这是因为我看到了如何使用累加器来反转列表,现在我似乎能够解决问题的唯一方法是使用类似的程序,它给出了答案,但也反转了列表.

I'm having a problem where my answer for every Prolog problem I'm posed ends up with the answer list being reversed. It's because I was shown how to use an accumulator to reverse a list, and now the only way I seem to be able to solve a problem is to use a similar program, which gives the answer, but also reverses the list.

例如,当被要求编写一个程序,用第三个参数替换第一个参数中第二个参数的所有实例,并给出结果列表作为第四个参数时,我写了以下代码:

For example, when asked to write a program which replaces all instances of the second argument inside the first argument with the third argument, and gives the resulting list as it's fourth argument, I wrote this code:

replace(L, A, B, X):-  
    accrep(L, [], A, B, X).   

accrep([H | T], Y, A, B, X):-
    H = A,  
    accrep(T, [B | Y], A, B, X). 

accrep([H | T], Y, A, B, X):-  
    H \= A,  
    accrep(T, [H | Y], A, B, X). 

accrep([], X, _, _, X).

这确实在技术上解决了问题,但也颠倒了列表,这不是被要求的,我怀疑当我将正确答案向后递给他们时,任何人都会印象深刻.但是我想不出避免这种情况的方法,并且添加取消反转列表的代码似乎很荒谬,而我本来就不应该反转它.

This does indeed technically solve the problem, but also reverses the list, which wasn't asked for, and I doubt anyone would be impressed when I hand them the correct answer backwards. But I can't think of a way to avert this, and it seems ridiculous to add in code that unreverses the list, when I should never have reversed it in the first place.

谁能告诉我如何使用累加器而不会遇到这个问题?我在其他多个简单程序中也遇到了同样的问题.

Can anyone tell me how to use accumulators without running into this problem? I've had the same issue with multiple other simple programs too.

谢谢,亚历克斯.

推荐答案

我认为您使用累加器是因为您正在考虑程序解决方案.简单地避免它,您的代码会简单得多,并且会解决问题.这是一个开始,请完成它.

I think you use an accumulator because you're thinking to a procedural solution. Simply avoid it, your code will be far simpler, and will solve the problem. Here is a start, please complete it.

replace(L, A, B, X):-
    accrep(L, A, B, X).

accrep([], _, _, []).
accrep([A|R], A, B, [B|S]) :- accrep(R, A, B, S).
....

这篇关于Prolog 累加器反转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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