01 · Overview
About Potigol
Potigol is an educational programming language with Portuguese syntax and support for imperative, functional, and object-oriented programming. Its official documentation highlights static typing with inference, functions, lists, tuples, custom types, and pattern matching.
This page describes Potigol using the project's references. Additional libraries such as Jerimum extend what a program can do without becoming part of Potigol's core syntax.
02 · Organization
Basic structure
A file can begin directly with declarations and instructions. Simple examples do not need an outer programa block or a main function.
# A sequence of instructions
nome = "Mundo"
escreva "Olá, {nome}!"
soma(a: Inteiro, b: Inteiro) = a + b
escreva soma(2, 3)
Instructions can be expressions, declarations, calls, assignments, or blocks that end with fim. Functions and types can also be declared in the file.
03 · Writing
Names and comments
- Identifiers start with a letter and may contain letters, accents, digits, and underscores.
- Keywords and type names use Portuguese terms such as
se,então,Inteiro, andLógico. - Line comments start with
#. - Text uses double quotes; expressions inside braces are interpolated.
# Comment
aluna = "Lia"
nota = 8.5
escreva "{aluna} obteve {nota}"
04 · Data
Types and variables
| Type | Example or use |
|---|---|
Inteiro | Integer numbers. |
Real | Numbers with a fractional part. |
Texto | Strings in double quotes. |
Caractere | A single character, such as 'A'. |
Lógico | verdadeiro or falso. |
Lista[T] | A sequence of values of type T. |
Tupla | An ordered group of values, including different types. |
Assignment with = creates a value that cannot be reassigned. Use var for a mutable variable and := to update it. Types are inferred when omitted and remain fixed while the program runs.
pontos = 10
var tentativas := 0
tentativas := tentativas + 1
nome: Texto = "Lia"
idade: Inteiro = 14
Parallel assignment binds several values in one instruction, for example a, b = 3, 7.
05 · Expressions
Operators
| Category | Operators | Use |
|---|---|---|
| Arithmetic | + - * / div mod ^ | Arithmetic, integer division, remainder, and exponentiation. |
| Comparison | == <> > >= < <= | Equality, inequality, and ordering. |
| Logical | nao e ou | Negation, conjunction, and disjunction. |
| Lists | ::, + | Prepend an item or concatenate lists. |
Parentheses make evaluation order explicit. :: prepends an item: 0 :: [1, 2] produces [0, 1, 2].
06 · Interaction
Input and output
escreva prints an expression and advances to the next line; imprima writes without that line break. leia_inteiro, leia_numero, and leia_texto read values of the specified type. The documentation also describes multiple-value and list input.
imprima "Digite seu nome: "
nome = leia_texto
escreva "Olá, {nome}!"
escreva "Digite dois números:"
a, b = leia_inteiro
escreva "{a} + {b} = {a + b}"
In a string, {expression} inserts its value. Potigol also documents formatting with the value formato pattern expression.
07 · Flow
Conditions and loops
se and escolha express decisions. Blocks can be used as instructions or as expressions that produce a value.
mensagem = se nota >= 7 então
"Aprovada"
senão
"Continue praticando"
fim
escolha nota
caso 10 => "Excelente"
caso n se n >= 7 => "Aprovada"
caso _ => "Estude mais"
fim
Loops include para and enquanto. para iterates over a range or a collection and can take a step value.
para i de 1 até 3 faça
escreva i
fim
var n := 3
enquanto n > 0 faça
escreva n
n := n - 1
fim
08 · Reuse
Functions and collections
A short function can be written as an expression. Functions with several instructions end with fim; the final expression supplies the result, or retorne can state it explicitly. Functions also support typed parameters and recursion.
dobro(n: Inteiro) = n * 2
fatorial(n: Inteiro): Inteiro
se n <= 1 então
1
senão
n * fatorial(n - 1)
fim
fim
Lists and tuples organize values. Lists can be transformed with mapeie, filtered with selecione, and reduced with injete. Potigol's documentation uses one-based list indexes.
numeros = [1, 2, 3, 4]
dobros = numeros.mapeie(n => n * 2)
pares = numeros.selecione(n => n mod 2 == 0)
coordenada = (3.5, 2.0)
09 · Modeling
Composite types and object-oriented programming
tipo declares structures with attributes and methods. Create a value by calling the type with its attribute values; methods can be used as properties or functions.
tipo Pessoa
nome: Texto
saudacao() = "Olá, {nome}!"
fim
aluna = Pessoa("Lia")
escreva aluna.saudacao
Tuples
Tuples are ordered, immutable, fixed-size collections whose elements can have different types. Each position has a stable meaning and can be read with properties such as .primeiro, .segundo and .terceiro.
ponto = (3.5, 4.2)
aluna = ("Lia", 14, 8.5)
escreva ponto.primeiro
escreva ponto.segundo
escreva aluna.terceiro
Use a tuple to group related data or organize several values produced by a function. For homogeneous collections whose size can change, use a list.
The official documentation also covers abstract types, inheritance, generics, functions as values, and pattern matching.
10 · Built-in operations
Math and text
Potigol provides mathematical operations for numbers and methods for inspecting or transforming text. Their names remain in Portuguese; check each result's type before combining it with another expression.
| Group | Documented forms | Purpose |
|---|---|---|
| Constant and trigonometry | PI, sen(x), cos(x), tg(x), arcsen(x), arccos(x), arctg(x) | Constant π and trigonometric functions. |
| Math | abs(x), raiz(x), log(x), log10(x), aleatório(...) | Absolute value, square root, logarithms, and random values. |
| Text | .tamanho, .posição(c), .contém(c), .maiúsculo, .minúsculo, .inverta | Check length, search for characters, and transform text. |
| Text fragments | .divida, .pegue(n), .descarte(n), .cabeça, .cauda, .último | Split, slice, or inspect characters. |
raio = 3.0
area = PI * raio ^ 2
frase = "lógica e programação"
partes = frase.divida(" ")
escreva "Área: {area}"
escreva "A frase tem {frase.tamanho} caracteres"
escreva partes
Text can also be concatenated with +. The conversions .inteiro and .real read the beginning of numeric text; validate free-form input before using it in a calculation.
11 · Collections
Lists in detail
A list keeps its elements in order and is immutable by default: insertion, removal, and updates produce a new list. Indexes start at 1, unlike the common convention in other pseudolanguages documented here.
| Operation | Example | Effect |
|---|---|---|
| First and rest | lista.cabeça, lista.cauda | Read the first element and the list without it. |
| Position | lista[1], lista.último | Read by index or get the last element. |
| Size and membership | lista.tamanho, lista.contém(valor) | Count elements or check whether a value is present. |
| Slice | lista.pegue(n), lista.descarte(n) | Keep or remove the first n elements. |
| New list | lista.insira(i, valor), lista.remova(i), lista.atualize(i, valor) | Insert, remove, or replace an element by index. |
| Composition | a + b, valor :: lista | Concatenate lists or prepend a value. |
original = [2, 4, 6, 8]
var atualizada := original
atualizada[2] := 5
escreva original # [2, 4, 6, 8]
escreva atualizada # [2, 5, 6, 8]
:= updates a mutable variable, but does not change the list still referenced by original. Methods such as .atualize, .insira, and .remova make the new-list result explicit.
12 · Abstraction
Functional programming
A function can receive another function as an argument or return one as its result. Lambda expressions, written with =>, describe short operations without declaring a named function.
numeros = [1, 2, 3, 4, 5, 6, 7, 8]
pares = numeros.selecione(n => n mod 2 == 0)
dobros = pares.mapeie(n => n * 2)
soma = numeros.injete(0)((total, n) => total + n)
aplique(f: Inteiro => Inteiro, valor: Inteiro) = f(valor)
sucessor(n: Inteiro) = n + 1
escreva aplique(sucessor, 5)
selecionekeeps elements that satisfy a condition.mapeietransforms each element and returns a list.injetetraverses a collection and combines its elements with an initial accumulator.
These operations do not change the source list. Parameter and result types help check whether a transformation matches its data.
List comprehension
A comprehension combines one or more generator sequences with an expression to produce a new list. Each generator can depend on values from earlier generators.
somas = para i de 1 até 3,
j de i + 1 até 3 gere
i + j
fim
escreva somas
Currying
A curried function receives its arguments in stages: each partial call returns another function. This makes it possible to save a configured function for reuse.
soma(a: Inteiro) = ((b: Inteiro) => a + b)
soma_dois = soma(2)
escreva soma(2)(3)
escreva soma_dois(4)
Tail recursion
In tail recursion, the recursive call is the last operation in the case. Potigol's documentation presents this form with optimization, suited to recursive traversals that carry an accumulator.
conta(n: Inteiro, acumulado: Inteiro): Inteiro = escolha n
caso 0 => acumulado
caso restante => conta(restante - 1, acumulado + 1)
fim
escreva conta(1000, 0)
13 · Structural decisions
Pattern matching
escolha can compare a value against cases or inspect a list's structure. The [] pattern represents an empty list; cabeça :: cauda separates its first element from the rest. The _ pattern accepts any value, and an extra condition can narrow a case.
quantidade(itens: Lista[Inteiro]): Inteiro = escolha itens
caso [] => 0
caso _ :: restante => 1 + quantidade(restante)
fim
classifique(n: Inteiro) = escolha n
caso valor se valor < 0 => "negativo"
caso 0 => "zero"
caso _ => "positivo"
fim
escreva quantidade([3, 5, 8])
escreva classifique(-2)
Cases are checked in order, so put specific patterns before a broad one such as _. In recursive functions, the empty-list case provides the stopping condition.
14 · Game library
Jerimum: games with Potigol
Jerimum is a game library for Potigol. Its official repository contains examples and modules for opening a window, drawing images and text, reading keyboard and mouse input, tracking time, and playing audio. It adds game features to Potigol programs and remains separate from Potigol's core syntax.
Startup and the game loop
A program starts with use "jerimum" and defines atualize() to update game state and desenhe() to register drawing operations. jogo.iniciar receives a title, width, height, the two functions, and an optional frame rate that defaults to 60.
use "jerimum"
atualize()
# Atualize o estado do jogo
fim
desenhe()
# Registre imagens e textos do quadro
fim
jogo.iniciar("Meu jogo", 640, 480, atualize, desenhe, 60)
jogo exposes largura, altura, título, and fps. The source creates a fixed-size window with Swing/AWT. Jogo.distância, Jogo.projeção_X, and Jogo.projeção_Y support movement calculations; projection angles are given in degrees.
Drawing, layers, and images
Imagem("file.png") loads an image. desenhe(x, y, z) places it at coordinates on an integer layer. Higher-numbered layers are drawn in front. The library also provides centered drawing, rotation, scaling, and sprite-sheet slicing with fatie.
fundo = Imagem("fundo.png")
nave = Imagem("nave.png")
quadros = Imagem.fatie("explosao.png", 32, 32)
desenhe()
fundo.desenhe(0, 0, 0)
nave.desenhe_centralizado(320, 240, 2, 0)
fim
Animacao(velocidade, imagens) selects images from a sequence based on elapsed time.
Keyboard, mouse, and time
Teclado exposes logical values such as TECLA_PARA_DIREITA, TECLA_ENTER, and TECLA_A through TECLA_Z. Mouse.x and Mouse.y report the pointer position; Mouse.BOTAO_ESQUERDO and Mouse.BOTAO_DIREITO report button states. Relógio.milisegundos counts time since initialization.
var x := 100
atualize()
se Teclado.TECLA_PARA_DIREITA então x := x + 4 fim
se Mouse.BOTAO_ESQUERDO então x := Mouse.x fim
fim
Text, colors, audio, and files
Fonte(tamanho) creates a font. Its drawing methods accept text, coordinates, a layer, and a color. Cor(vermelho, verde, azul) creates an RGB color; constants include Cor.BRANCO, Cor.PRETO, and Cor.VERDE.
Som("efeito.wav") plays an effect with toque(). Musica("faixa.wav") provides toque, pause, continue, pare, and tocando; playback loops by default. Arquivo.leia("dados.txt") returns the file's lines as a list.
| Module | Main calls | Purpose |
|---|---|---|
Jogo | iniciar, distância, projeção_X, projeção_Y | Window, update loop, and geometry. |
Imagem | desenhe, desenhe_centralizado, fatie | Load, draw, transform, and slice images. |
Animacao | Animacao(...), imagem() | Select animation frames. |
Teclado and Mouse | Keys, buttons, x/y | Read input. |
Fonte and Cor | Fonte(tamanho), Cor(r, g, b) | Draw colored text. |
Som and Musica | toque, pause, continue, pare | Effects and music. |
Relógio and Arquivo | milisegundos, leia | Read time and file lines. |
Example: move an image
use "jerimum"
nave = Imagem("nave.png")
var x := 300
var y := 220
atualize()
se Teclado.TECLA_PARA_DIREITA então x := x + 4 fim
se Teclado.TECLA_PARA_ESQUERDA então x := x - 4 fim
se Teclado.TECLA_PARA_CIMA então y := y - 4 fim
se Teclado.TECLA_PARA_BAIXO então y := y + 4 fim
fim
desenhe()
nave.desenhe_centralizado(x, y, 1)
fim
jogo.iniciar("Movimento", 640, 480, atualize, desenhe)
Method details are in the Jerimum documentation and source code. The library uses Java facilities for windows, drawing, and audio; its examples describe desktop Potigol programs.
15 · Combined example
Calculate an average
media(a: Real, b: Real, c: Real) = (a + b + c) / 3
escreva "Digite três notas:"
a, b, c = leia_numero
resultado = media(a, b, c)
se resultado >= 7 então
escreva "Aprovada: {resultado}"
senão
escreva "Em recuperação: {resultado}"
fim
16 · Further reading
References
- Official Potigol documentation, including syntax, structures, functions, types, lists, and tuples.
- Official references for numbers, text, math, and functions.
- Official references for lists, tuples, and functional programming, with list comprehensions, lambda expressions, currying, tail recursion, and pattern matching.
- Official Potigol repository and its published grammar.
- Official Jerimum repository, with documentation and examples.
- References for Jogo, Imagem, Teclado, Mouse, Fonte, and Cor; the source code also describes audio, animation, and file reading.