如何重写以下内容以使其使用 if_? [英] How do I rewrite the following so it uses if_?

查看:20
本文介绍了如何重写以下内容以使其使用 if_?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些简单的练习 感受一下语言.

I am doing some easy exercises to get a feel for the language.

is_list([]).
is_list([_|_]).

my_flatten([],[]).
my_flatten([X|Xs],RR) :-
   my_flatten(Xs,R),
   (is_list(X), !, append(X,R,RR); RR = [X | R]).

这是一个使用 cut 的版本,用于将列表展平一级的谓词.

Here is a version using cut, for a predicate that flattens a list one level.

my_flatten([],[]).
my_flatten([X|Xs],RR) :-
   my_flatten(Xs,R),
   if_(is_list(X), append(X,R,RR), RR = [X | R]).

这是我想写的,但它不起作用.is_list(X) = true 也不作为 if_ 条件.我打算如何在这里使用 if_?

Here is how I want to write it, but it does not work. Neither does is_list(X) = true as the if_ condition. How am I intended to use if_ here?

推荐答案

在 Prolog 中,if … 的等价物然后 …else … 在其他语言中是:

In Prolog, the equivalen of an if … then … else … in other languages is:

(condition -> if-true; if-false)

带有条件if-trueif-false 您需要填写的项目.

With condition, if-true and if-false items you need to fill in.

因此,在这种特定情况下,您可以通过以下方式实现:

So in this specific case, you can implement this with:

my_flatten([],[]).
my_flatten([X|Xs],RR) :- 
    my_flatten(Xs,R),
    (  is_list(X)
    -> append(X,R,RR)
    ; RR = [X | R] ).

或者我们可以递归地展平:

or we can flatten recursively with:

my_flatten([],[]).
my_flatten([X|Xs],RR) :- 
    my_flatten(Xs,R),
    (  flatten(X, XF)
    -> append(XF,R,RR)
    ; RR = [X | R] ).

您的 if_/3 谓词 用于 reified 谓词em>.

Your if_/3 predicate is used for reified predicates.

这篇关于如何重写以下内容以使其使用 if_?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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