Logo: C Cpp To Lean4 Translator

C Cpp To Lean4 Translator

Communautéit
ArabelaTso
c-cpp-to-lean4-translator

Iwwersetzt C- oder C++-Programmer an entspriechende Lean4-Code, erhält d’Semantik vum Programm a stellt sécher, datt de generéierte Code korrekt typiséiert an ausféierbar ass a funktionéiert. Benotzt dës Skill, wann de Benotzer C/C++-Code a Lean4 ëmwandelen oder portéieren, imperativen Code a funktionelle Lean4 iwwersetzen oder Lean4-Versioune vu C/C++-Algorithme erstellen wëllt.

Add to TypingMind

Iwwersiicht

EditeurArabelaTso
RepositorySkills-4-SE
Skill-Nummc-cpp-to-lean4-translator
Stären
258
Forks
25
Matgeliwwert Dateien
1
LizenzApache-2.0
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • 1 matgeliwwert Dateien

    Skripten, Virlagen a Referenzen, déi de Modell beim Schaffe liese kann. D'Dateie kënnen nëmme gelies ginn a ginn ni ausgeféiert.

  • Open Source

    ArabelaTso huet de Skill op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill C Cpp To Lean4 Translator an TypingMind, fir e mat all LLM ze benotzen, oder setzt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vu GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier, déi hei drënner steet, an a bestätegt d'Installatioun.
    https://github.com/ArabelaTso/Skills-4-SE/tree/main/skills/c-cpp-to-lean4-translator
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill derbäisetzen → Iwwer eng GitHub-URL. Pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an d'Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/ArabelaTso/Skills-4-SE.git /tmp/Skills-4-SE
mkdir -p .claude/skills
cp -r /tmp/Skills-4-SE/skills/c-cpp-to-lean4-translator .claude/skills/c-cpp-to-lean4-translator
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert C Cpp To Lean4 Translator an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet C Cpp To Lean4 Translator automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass C Cpp To Lean4 Translator net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Schlësselen.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

C/C++ to Lean4 Translator

Overview

Transform C or C++ programs into equivalent Lean4 code that preserves the original semantics while leveraging Lean4's functional programming paradigm, strong type system, and proof capabilities.

Translation Workflow

Step 1: Analyze Input Code

Understand the C/C++ program structure and semantics:

  1. Identify program components:

    • Functions and their signatures
    • Data structures (structs, classes, arrays)
    • Control flow patterns (loops, conditionals)
    • Memory management (allocation, pointers)
    • I/O operations
    • Dependencies and includes
  2. Understand semantics:

    • What does the program compute?
    • What are the inputs and outputs?
    • Are there side effects?
    • What are the invariants and preconditions?
  3. Note translation challenges:

    • Pointer arithmetic
    • Mutable state
    • Imperative loops
    • Manual memory management
    • Undefined behavior

Step 2: Design Lean4 Structure

Plan the Lean4 equivalent before writing code:

  1. Choose appropriate types:

    • Int for signed integers
    • Nat for unsigned integers and array indices
    • Float for floating-point numbers
    • Array for dynamic arrays
    • List for linked lists
    • Custom structure types for structs/classes
  2. Determine purity:

    • Pure functions: return values directly
    • Side effects: use IO monad
    • Mutable state: use IO.Ref or ST monad
  3. Plan control flow translation:

    • Loops → Recursive functions
    • Mutable variables → Function parameters
    • Early returns → Conditional expressions
  4. Handle memory:

    • Stack allocation → Direct values
    • Heap allocation → Automatic memory management
    • Pointers → Direct values or references

Step 3: Translate Code

Follow these translation principles:

Functions

Pattern: Pure function

c
// C/C++
int add(int a, int b) {
    return a + b;
}
lean
-- Lean4
def add (a b : Int) : Int :=
  a + b

Pattern: Function with side effects

c
// C/C++
void printSum(int a, int b) {
    printf("%d\n", a + b);
}
lean
-- Lean4
def printSum (a b : Int) : IO Unit :=
  IO.println (a + b)
Control Flow

Pattern: If-else

c
// C/C++
int max(int a, int b) {
    if (a > b) return a;
    else return b;
}
lean
-- Lean4
def max (a b : Int) : Int :=
  if a > b then a else b

Pattern: For loop → Tail recursion

c
// C/C++
int sum(int n) {
    int result = 0;
    for (int i = 0; i < n; i++) {
        result += i;
    }
    return result;
}
lean
-- Lean4
def sum (n : Nat) : Nat :=
  let rec loop (i acc : Nat) : Nat :=
    if i >= n then acc
    else loop (i + 1) (acc + i)
  loop 0 0

Pattern: While loop → Recursion

c
// C/C++
int factorial(int n) {
    int result = 1;
    while (n > 1) {
        result *= n;
        n--;
    }
    return result;
}
lean
-- Lean4
def factorial (n : Nat) : Nat :=
  let rec loop (n acc : Nat) : Nat :=
    if n <= 1 then acc
    else loop (n - 1) (acc * n)
  loop n 1
Data Structures

Pattern: Struct

c
// C/C++
struct Point {
    int x;
    int y;
};
lean
-- Lean4
structure Point where
  x : Int
  y : Int
  deriving Repr

Pattern: Array

c
// C/C++
int arr[5] = {1, 2, 3, 4, 5};
lean
-- Lean4
def arr : Array Int := #[1, 2, 3, 4, 5]
Pointers and References

Key principle: Lean4 doesn't have raw pointers. Translate based on usage:

  • Read-only pointers: Pass by value
  • Output parameters: Return values (use tuples for multiple returns)
  • Mutable references: Use IO.Ref or return new values
c
// C/C++ - Output parameter
void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}
lean
-- Lean4 - Return tuple
def swap (a b : Int) : Int × Int :=
  (b, a)

Step 4: Ensure Type Correctness

Lean4's type system is strict. Address common type issues:

  1. Integer types:

    • Use Nat for non-negative values (array indices, counts)
    • Use Int for potentially negative values
    • Convert explicitly: n.toNat, n.toInt
  2. Array bounds:

    • Lean4 requires proof of valid indices
    • Use safe accessors: arr.get?, arr[i]?
    • Or use arr[i]! with runtime check
  3. Division:

    • Natural number division: n / m (rounds down)
    • Integer division: use Int.div
    • Handle division by zero explicitly
  4. Type annotations:

    • Add explicit types when inference fails
    • Use : Type for clarity

Step 5: Test and Verify

Ensure the translated code works correctly:

  1. Compile check:

    bash
    lake build
  2. Create test cases:

    lean
    #eval add 2 3        -- Should output 5
    #eval factorial 5    -- Should output 120
  3. Compare outputs:

    • Run original C/C++ program
    • Run translated Lean4 program
    • Verify outputs match for same inputs
  4. Handle edge cases:

    • Empty arrays
    • Zero values
    • Negative numbers
    • Boundary conditions

Step 6: Optimize and Refine

Improve the translated code:

  1. Use Lean4 idioms:

    • Replace manual recursion with List.foldl, Array.foldl
    • Use pattern matching instead of nested if-else
    • Leverage standard library functions
  2. Add documentation:

    lean
    /-- Calculate the sum of first n natural numbers -/
    def sum (n : Nat) : Nat :=
      n * (n + 1) / 2
  3. Consider performance:

    • Use tail recursion for loops
    • Prefer Array over List for random access
    • Use @[inline] for small functions

Common Translation Patterns

For detailed patterns, see translation_patterns.md.

Quick Reference

C/C++Lean4
int xdef x : Int
unsigned int xdef x : Nat
float xdef x : Float
bool xdef x : Bool
char* strdef str : String
int arr[]def arr : Array Int
struct Sstructure S where
for (...)let rec loop ...
while (...)let rec loop ...
if (...) {...}if ... then ... else ...
switch (...)match ... with
return xx (last expression)
void f()def f : IO Unit
printf(...)IO.println ...

Examples

Example 1: Simple Algorithm

C/C++ Input:

c
int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

Lean4 Output:

lean
def gcd (a b : Nat) : Nat :=
  if b = 0 then a
  else gcd b (a % b)

Example 2: Array Processing

C/C++ Input:

c
int findMax(int arr[], int size) {
    int max = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

Lean4 Output:

lean
def findMax (arr : Array Int) : Option Int :=
  if arr.isEmpty then
    none
  else
    some (arr.foldl max arr[0]!)

Example 3: Struct with Methods

C/C++ Input:

cpp
struct Rectangle {
    int width;
    int height;

    int area() {
        return width * height;
    }

    int perimeter() {
        return 2 * (width + height);
    }
};

Lean4 Output:

lean
structure Rectangle where
  width : Nat
  height : Nat
  deriving Repr

def Rectangle.area (r : Rectangle) : Nat :=
  r.width * r.height

def Rectangle.perimeter (r : Rectangle) : Nat :=
  2 * (r.width + r.height)

Example 4: I/O Program

C/C++ Input:

c
#include <stdio.h>

int main() {
    int n;
    printf("Enter a number: ");
    scanf("%d", &n);
    printf("Factorial: %d\n", factorial(n));
    return 0;
}

Lean4 Output:

lean
def factorial (n : Nat) : Nat :=
  if n <= 1 then 1
  else n * factorial (n - 1)

def main : IO Unit := do
  IO.print "Enter a number: "
  let input ← IO.getStdIn >>= (·.getLine)
  match input.trim.toNat? with
  | some n =>
    IO.println s!"Factorial: {factorial n}"
  | none =>
    IO.println "Invalid input"

Best Practices

  1. Start simple: Translate basic functions first, then build up complexity
  2. Preserve semantics: Ensure the Lean4 code computes the same results
  3. Use types wisely: Leverage Lean4's type system for correctness
  4. Embrace immutability: Prefer pure functions over mutable state
  5. Test thoroughly: Verify outputs match for various inputs
  6. Document assumptions: Note any semantic differences or limitations
  7. Leverage standard library: Use built-in functions when available
  8. Handle errors gracefully: Use Option or Except for error cases

Limitations and Considerations

  1. Undefined behavior: C/C++ undefined behavior must be handled explicitly in Lean4
  2. Performance: Functional code may have different performance characteristics
  3. Concurrency: C/C++ threading requires different approaches in Lean4
  4. Low-level operations: Bit manipulation and pointer arithmetic need careful translation
  5. External libraries: C/C++ library calls may not have direct Lean4 equivalents
  6. Macros: C preprocessor macros need manual translation
  7. Templates: C++ templates translate to Lean4 generics differently

Resources

Matgeliwwert Dateien

De Modell liest dës Dateie bei Bedarf, wärend de Skill gelueden ass. Si ginn als liesbar Dateie bereetgestallt a ginn ni ausgeféiert.

Heefeg gestallte Froen

Wat mécht de KI-Skill C Cpp To Lean4 Translator?

Iwwersetzt C- oder C++-Programmer an entspriechende Lean4-Code, erhält d’Semantik vum Programm a stellt sécher, datt de generéierte Code korrekt typiséiert an ausféierbar ass a funktionéiert. Benotzt dës Skill, wann de Benotzer C/C++-Code a Lean4 ëmwandelen oder portéieren, imperativen Code a funktionelle Lean4 iwwersetzen oder Lean4-Versioune vu C/C++-Algorithme erstellen wëllt.

Firwat C Cpp To Lean4 Translator op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. C Cpp To Lean4 Translator besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt, amplaz en Abonnement pro Benotzerplaz ze bezuelen. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech C Cpp To Lean4 Translator an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/ArabelaTso/Skills-4-SE/tree/main/skills/c-cpp-to-lean4-translator an. TypingMind liest d'Datei SKILL.md, bëndelt déi zougehéiereg Dateien an installéiert dat Ganzt als Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen C Cpp To Lean4 Translator benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat C Cpp To Lean4 Translator benotzen?

Esou vill wéi Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir C Cpp To Lean4 Translator domat benotzen – zum Beispill mat GPT, Claude, Gemini, Grok, DeepSeek, Mistral oder Llama – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill C Cpp To Lean4 Translator gratis?

Jo. ArabelaTso huet de Skill ënner der Lizenz Apache-2.0 op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbare Pak vun Instruktiounen, deen engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt e maache soll a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a kee Lafzäitëmfeld a funktionéiere mat all Modell.

Alleguer weisen

Elo Ären eegene KI-Aarbechtsberäich ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇