我们如何在序言中表示复整数加法和乘法? [英] how do we represent complex integers addition and multiplication in prolog?

查看:57
本文介绍了我们如何在序言中表示复整数加法和乘法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Prolog 语言的新手,正在尝试自学.我遇到了一个有趣的问题,它说:

I'm new to Prolog language, trying to teach myself. I came across an interesting question which says:

将一个复整数表示为一个二元整数列表,所以 [2,5] 表示 2+5i.
编写 Prolog 谓词

Represent a complex integer as a two-element list of integers, so [2,5] represents 2+5i.
Write Prolog predicates

 cadd/3
 cmult/3

表示复整数加法和乘法.例如,

representing complex integer addition and multiplication. Thus for instance,

 cadd([X1,X2],[Y1,Y2],[Z1,Z2])

当且仅当 Z1=X1+Y1Z2=X2+Y2 时成功.
请注意,复数乘法不仅仅是复数加法.

succeeds if and only if Z1=X1+Y1 and Z2=X2+Y2.
Note that complex number multiplication is not just like complex number addition.

我是新手.有人可以帮忙吗,我正在尝试自学.非常感谢您的帮助!

I'm new to this. Can someone help, I am trying to teach myself. Would really appreciate the help!

注意:仅用于学习目的!

推荐答案

扩展我对复数表示的评论.考虑:

Expanding on my comment on the complex number representation. Consider:

| ?- write_canonical([2,3]).
'.'(2,'.'(3,[]))
yes

| ?- write_canonical(c(2,3)).
c(2,3)
yes

| ?- arg(2, [2,3], Arg).
Arg = [3]
yes

| ?- arg(2, c(2,3), Arg).
Arg = 3
yes

替代表示也可以可视化为:

The alternative representations can be also visualized as:

    c               .
   / \             / \
  2   3           2   .
                     / \
                    3   []

重用 Will Ness 答案:

Reusing Will Ness answer:

:- use_module( library( clpfd)).   % in SWI Prolog

cadd(c(X1,X2), c(Y1,Y2), c(Z1,Z2)) :-
  %% succeeds if and only if Z1=X1+Y1 and Z2=X2+Y2.
  Z1 #= X1 + Y1,
  Z2 #= X2 + Y2.

如果您的 Prolog 系统不支持约束:

If your Prolog system doesn't support constraints:

cadd(c(X1,X2), c(Y1,Y2), c(Z1,Z2)) :-
  %% succeeds if and only if Z1=X1+Y1 and Z2=X2+Y2.
  Z1 is X1 + Y1,
  Z2 is X2 + Y2.

示例调用:

| ?- [user].
compiling user for byte code...
    cadd(c(X1,X2), c(Y1,Y2), c(Z1,Z2)) :-
      %% succeeds if and only if Z1=X1+Y1 and Z2=X2+Y2.
      Z1 is X1 + Y1,
      Z2 is X2 + Y2.

user compiled, 4 lines read - 679 bytes written, 1921 ms

| ?- cadd(c(2,3), c(-2,1), C).
C = c(0,4)
yes

这篇关于我们如何在序言中表示复整数加法和乘法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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