Es-parrot-parrot-examples

提供:Dev Guides
移動先:案内検索

オウム-プログラムのプログラム

Parrotprogramaciónes同様のal lenguaje ensambladorprogramacióny tienes la oportunidad de trabajar en un nivel inferior。 番組表のプログラムリストは、プログラムロロのさまざまな側面に対応しています。

  • リンク:/parrot/parrot_examples#parrot_hello_world [ClásicoHola mundo!]
  • リンク:/parrot/parrot_examples#parrot_registers [Utilizando registros]
  • リンク:/parrot/parrot_examples#parrot_squares [再開広場]
  • リンク:/parrot/parrot_examples#parrot_fibonacci [ヌメロスデフィボナッチ]
  • リンク:/parrot/parrot_examples#parrot_factorial [Facttorialinformática]
  • リンク:/parrot/parrot_examples#parrot_pbc [Compilciónde PBC] *リンク:/parrot/parrot_examples#parrot_pir [PIR vs. PASM]

[#parrot_hello_world]#ClásicoHola mundo!#

Cree un archivo llamado hello.pir que contiene el siguientecódigo:

.sub _main
   print "Hello world!\n"
   end
.end

継続的で、次のようになります:

parrot hello.pir

コモ時代、エスペラー、テキスト「Hello world!」 en la consola、seguido de uncarácterde nuevalínea(debido a la \ n)。

前方にある '.sub _main' de los estados que las instrucciones que se detallan acontinuaciónconstituyen una subrutina llamada '_main'、hasta que un '.end' han encontrado。 La segundalíneacontiene lainstruccióndeimpresión。 そのためには、カセプタとコンセプテアトカデナの両方のインストラクションがあります。 エル・サンサンブラー・デ・エンカルガ・デ・デシル・ケ・ヴァリアント・デ・ラス・インストルチオンズ・デ・ウーソ・パラ・ノソトロス。 La terceralínea、el 'end' instrucciones、lo que provoca que elintérpretepara terminar。

[#parrot_registers] #Utilizando Registros#

Podemos modificar hola.pir a prima tienda la cadena Hello world!\ n登録なし、継続的、実用的、登録済み、実用的です。

.sub _main
   set S1, "Hello world!\n"
   print S1
   end
.end

Aquíhemos dicho exactamente que registrar para usar。 S1によるSinの禁輸措置は、Parrotのレジストラに登録されている$ S1ポデモです。 Tambiénes posible utilizar un =notaciónen lugar de escribir las instrucciones。

.sub _main
   $S0 = "Hello world!\n"
   print $S0
   end
.end

PIR para que seaaúnmás読みやすい、llamado registros pueden ser utilizados。 エストスの息子は、本当の登録番号です。

.sub _main
   .local string hello
   hello = "Hello world!\n"
   print hello
   end
.end

エル '.local’ディレクティバインディカque el registrosóloes necesario dentro de la misma unidad decompilación(es decir、entre .sub y .final)。 Despuésde un '.local' es un tipo。 Esto puede ser int(para I registros)、flotación(para N registros)、cadena(para S registros)、pmc(para P registros)またはel nombre de un tipo。

[#parrot_squares] #Resumen plazas#

Este ejemplo presenta algunasmásinstrucciones y sintaxis PIR。 Laslíneasque comienzan con#son comentarios。

.sub _main
   # State the number of squares to sum.
   .local int maxnum
   maxnum = 10

   # Some named registers we'll use.
   # Note how we can declare many
   # registers of the same type on one line.
   .local int i, total, temp
   total = 0

   # Loop to do the sum.
   i = 1

loop:
   temp = i* i
   total += temp
   inc i
   if i <= maxnum goto loop

   # Output result.
   print "The sum of the first "
   print maxnum
   print " squares is "
   print total
   print ".\n"
   end
.end

PIR proporciona un poco deazúcarsintácticaque lo hacen vermásalto nivel de la asamblea。 イェンプロによる:

temp = i * i

Es simplemente otra forma escribir elmásasamblea de ish:

mul temp, i, i

Y:

if i <= maxnum goto loop

エス・エル・ミスモ:

le i, maxnum, loop

Y:

total += temp

エス・エル・ミスモ:

add total, temp

コモ・レグラ将軍、ケ・ロ・ロ・インストラッシオン・モディフィカ・エル・コンテニド・デ・ウン・レジストロ、ケ・セラー・プライマー・レジストロ・クアンド・ポル・エスクリト・ラス・インストルキオン・エン・コンジャント。

共通の習慣と、いくつかの宣言の実装、および明確な前兆などの概念の実装があります。 続きを読むes uno de los lugares donde uso de goto no es una mala forma!

[#parrot_fibonacci]#Númerosde Fibonacci#

La serie de Fibonacci es definido como sigue:dosnúmeros、1 y 1。 継続的、多様性は、1、2、3、5、8、13、1、2、3、1、2、3、8、13、12、13、12、13、18、13、18、13、16、13、16、13、16、11、11、11、12、13、16、13、16、13、16、13、18、12、13、16、、13、18、、13、18、、17、、14、17、、、14、17、、14、17、17、17、17、17、17、17、17、17、17、17、17、17、17、13、17、14番 La serie de Fibonacci el fib(n)es el n’thnúmerode la serie。 彼は、単純なオウムのプログラムで、フィボナッチの20の入門書を考慮します。

# Some simple code to print some Fibonacci numbers

        print   "The first 20 fibonacci numbers are:\n"
        set     I1, 0
        set     I2, 20
        set     I3, 1
        set     I4, 1

REDO:   eq      I1, I2, DONE, NEXT

NEXT:   set     I5, I4
        add     I4, I3, I4
        set     I3, I5
        print   I3
        print   "\n"
        inc     I1
        branch  REDO
DONE:   end

Perlの同等のコード:

print "The first 20 fibonacci numbers are:\n";

my $i = 0;
my $target = 20;
my $a = 1;
my $b = 1;

until ($i == $target) {
   my $num = $b;
   $b += $a;
   $a = $num;
   print $a,"\n";
   $i++;
}
  • 注: *Es un buen punto deinterés、uno de losmáscortos y、sin duda、lamáshermosa manera de imprimir una serie de Fibonacci en Perl es perl -le '$ b = 1; print $ a + = $ b、mientras que print $ b + = $ a '。

[#parrot_factorial]#Cálculo階乗再帰#

たとえば、関数型の関数型と再帰型の関数型再帰関数を定義します。

.sub _fact
   # Get input parameter.
   .param int n

   # return (n > 1 ? n* _fact(n - 1) : 1)
   .local int result

   if n > 1 goto recurse
   result = 1
   goto return

recurse:
   $I0 = n - 1
   result = _fact($I0)
   result *= n

return:
   .return (result)
.end


.sub _main :main
   .local int f, i

   # We'll do factorial 0 to 10.
   i = 0

loop:
   f = _fact(i)

   print "Factorial of "
   print i
   print " is "
   print f
   print ".\n"

   inc i
   if i <= 10 goto loop

   # That's it.
   end
.end

Echemos un vistazo a _fact sub primero。 副主任としての前衛的、そして副主任としてのトドス・コエンザン・コンポネント・コン・ザン・コン・サブ・ラヤ・デ・サブルティナ。 エスト・セ・ハセ・シンプリメント・コモ・ウナ・マネラ・デ・モストラー・ケ・ラ・ラ・エティケタ・エス・グローバル・アンド・アン・特定のアンビト・デ・ウナ・サブルティナ。 重要な問題は、サブルチナスに見えることです。

入門書、.param int n、especifica que esta subrutina toma unparámetrode entero y que nosgustaríahacer referencia al registro que fue aprobada por el nombre n para el resto de la sub。

グラン・パルト・デ・ロ・ケ・シグ・セ・ハ・ヴィスト・エン・イエメンプロス・アンテリオレス、アパルト・デ・ラ・リネア・シギエンテ:

result = _fact($I0)

PIRを使用して、PASMのように明確に表されます。 入門書の登録、登録簿の登録$ I0および登録簿の登録は、海事記録の作成と編集を行ってください。 Otros queestánrelacionados con registros、acontinuación、configurar、seguido por _fact que se invoca。 una vez _fact devuelve el valor devuelto por _fact se coloca en el registro le da el nombre。

Justo antes de que el .fin de la _fact sub、.directiva de retorno se utiliza para garantizar el valor almacenado en el registro、denominado resultado se coloca en el registro correcto para que se vea como un valor de retorno en elcódigoque llama alサブ。

La llamada a _fact en principal funciona de la misma forma como el recursivo llamar a _fact dentro de la _fact subsímismo。 エル・ニコ・ビットはデ・ラ・ヌエバのシンタクシスes:プリンシパル、escritodespuésde .sub _mainをリストします。 デ・フォーマ・プレデターミダダ、PIR sup que laejecucióncomienza con la primera sub en el archivo。 主要なモデフィシャル・メディア・センターは、サブ・コンシジオン・パラ・イニシアー・コン・エル・マルカド・デ・ラ・サブカミシオン・コンサルタンツ・プリンシパル・コンサルタンツ。

[#parrot_pbc] #PBCのコンパイル#

PIRはバイトコードを使用し、拡張機能を使用します。拡張機能は.pbcを使用します。

Parrot -o factorial.cpp factorial.pir

[#parrot_pir] #PIR対 PASM#

PASMのPIRプエデトランスフォーム:

parrot -o hello.pasm hello.pir

El modo PASM para el ejemplo最終的な最終評価:

_main:
   set S30, "Hello world!\n"
   print S30
end

PASM登録簿の登録は必要ありません。 Tambiénno tiene el .sub y .final las directivas、en lugar de una etiqueta en el inicio de las instrucciones。