C Cpp To Lean4 Translator 标志

C Cpp To Lean4 Translator

社区
ArabelaTso
c-cpp-to-lean4-translator

将 C 或 C++ 程序转换为等效的 Lean4 代码,同时保留程序语义,并确保生成的代码类型正确、可执行且能够成功运行。用户要求将 C/C++ 代码转换为 Lean4、将 C/C++ 程序移植到 Lean4、将命令式代码转换为函数式 Lean4,或创建 C/C++ 算法的 Lean4 版本时使用。

Add to TypingMind

概览

发布者ArabelaTso
代码仓库Skills-4-SE
技能名称c-cpp-to-lean4-translator
星标数
258
复刻数
25
附带文件
1
许可协议Apache-2.0
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 1 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 ArabelaTso 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 C Cpp To Lean4 Translator AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/ArabelaTso/Skills-4-SE/tree/main/skills/c-cpp-to-lean4-translator
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

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
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 C Cpp To Lean4 Translator,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 C Cpp To Lean4 Translator。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 C Cpp To Lean4 Translator 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

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

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

C Cpp To Lean4 Translator AI 技能有什么作用?

将 C 或 C++ 程序转换为等效的 Lean4 代码,同时保留程序语义,并确保生成的代码类型正确、可执行且能够成功运行。用户要求将 C/C++ 代码转换为 Lean4、将 C/C++ 程序移植到 Lean4、将命令式代码转换为函数式 Lean4,或创建 C/C++ 算法的 Lean4 版本时使用。

为什么在 TypingMind 中使用 C Cpp To Lean4 Translator?

因为您只需安装一次,就能搭配任何模型使用。C Cpp To Lean4 Translator 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 C Cpp To Lean4 Translator?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/ArabelaTso/Skills-4-SE/tree/main/skills/c-cpp-to-lean4-translator。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 C Cpp To Lean4 Translator?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

C Cpp To Lean4 Translator 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 C Cpp To Lean4 Translator 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

C Cpp To Lean4 Translator AI 技能免费吗?

是的。ArabelaTso 已在 GitHub 上根据 Apache-2.0 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇