1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

generic preprocessor gppを使う [Rust]

Last updated at Posted at 2024-10-23

スクリプトに掛けるプリプロセッサについて。

僕はCに慣れているので、M4よりgppの方がいいような気がします。
M4は再帰変換が僕にとってはやりにくいです。

まずはインストール。ここでは試験環境はArch Linuxです。

$ yay -S gpp

rustのi32のpopを処理します。

popi32.gpp
#define popi32(A,B) let A:i32=match B.pop() { Some(value)=>value,None=>1 }

スクリプト

エラトステネスのふるいで素数を求めるスクリプトです。

sieve.gpp
#include  "popi32.gpp"

use std::env;
fn main() {
    let args: Vec<String> = env::args().collect();
    let n=&args[1];
    let n:i32=n.parse().unwrap();
    let f:Vec <i32>=sieve(n);
    let l:i32=f.len() as i32;
    println! ("{:?} : {:?} ",l,f);
}

fn sieve(n:i32)->Vec<i32> {
  let mut tab:Vec<i32>=(2..=n).rev().collect();
  let mut l:Vec<i32>=vec![];
  while !tab.is_empty() {
    popi32(v,tab);
    l.push(v);
    tab.retain(|&x| x%v !=0);
    }
  l
}

プリプロセッシング

$ gpp sieve.gpp > sieve.rs

コンパイル

$ rustc sieve.rs

実行

$ ./sieve 100
25 : [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97] 

うまくいきました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?