Pythonの組み込み関数とRustの対応関係


Rust 1.0 で動作を確認しています

1.0においても結構な数のAPIがunstableのままなので注意してください。



## abs
```rust
fn abs() {
    println!("abs(-1.5f32)={}", -1.5f32.abs());
    println!("abs(-2i32)={}", -2i32.abs());
}
```

## all
```rust
fn all() {
    // rangeはint型
    (0..10).all(|x| x % 2 == 0);
    // 通常のiteratorは&int型
    [2, 4].iter().all(|&x| x % 2 == 0);
    // rangeとiteratorで返す型が違うのは気持ち悪いので、常に参照を返すように
    // して欲しい
}
```

## any
```rust
fn any() {
    (0..10).any(|x| x == 9);
    [0, 1].iter().all(|x| *x == 1);
}
```

## ascii
残念ながら簡単にやる方法はunstable

```rust
fn ascii() {
    // unstable feature
    // println!("unicode escape is [{}]", "あいうえおabcde".escape_unicode());
    // println!("default escape is [{}]", "あいうえおabcde\n\t\r".escape_default());
}
```

## bin
```rust
fn bin() {
    // ２進数リテラルは0b0011みたいに定義できる
    let a = 0b1010; // == 10
    let b = format!("0b{:b}", 10);
    println!("{}", b);
}
```

## bytearray, bytes
```rust
fn bytearray() {
    // 1
    let x: Vec<char> = vec!['\x20', 'a'];
    // 2
    let mut y = Vec::new();
    write!(&mut y, "abcdeあいう");
    // 3
    let z = "あいう".bytes().collect::<Vec<u8>>();
}
```

## chr
```rust
fn chr() {
    println!("{:?}", std::char::from_u32(0x61));
}
```

## dict
```rust
fn dict() {
   let mut a = std::collections::HashMap::<&str, &str>::new();
   a.insert("a", "A");
}
```

## divmod
```rust
fn divmod() {
    let a = 5;
    let (b, c) = (a / 2, a % 2);
    println!("divmod: {}, {}", b, c);
}
```

## enumerate
```rust
fn enumerate() {
    // enumerate(start=1)のようなオプションは無い
    for (idx, x) in (1..3).enumerate() {
        println!("enumerate: {}, {}", idx, x);
    }
}
```

## filter
```rust
fn filter() {
    let x = [1, 2, 3, 4, 5];
    println!("filter: {:?}", x.iter().filter_map(|&x| if x % 2 == 0 {Some(x)} else {None}).collect::<Vec<i32>>());
    // Filter オブジェクト
    let y = x.iter().filter(|&x| *x % 2 == 0);
}
```

## float
```rust
fn float() {
    // from string
   let x = "-1.5e-1".parse::<f32>();
   // from integer
   let y = 100i32 as f32;
   let z = "inf".parse::<f32>();
   println!("float: {:?}, {:?}, {:?}", x, y, z);
}
```

## format
```rust
fn format() {
    let x = format!("{}, {}", "hello", "world!");
    println!("{}", x);
}
```

## frozenset, set
```rust
fn frozenset() {
    let mut x = std::collections::HashSet::<i32>::new();
    x.insert(0);
    x.insert(1);
    let y = x.clone();  // immutable
    let z: std::collections::HashSet<i32> = [1, 2, 3].iter().map(|&x| x).collect();
}
```

## hash
まだunstable

```rust
fn hash() {
    // unstable feature
    // println!("hash: {}", std::hash::hash::<_, std::hash::SipHasher>(&0));
}
```

## hex
```rust
fn hex() {
    let x = format!("0x{:x}, {}", 0x20, 0x20);
    println!("hex: {}", x);
}
```

## id
同一オブジェクトかどうか調べるには、アドレスを調べるほかない？

```rust
fn id() {
    let x = 1;
    let y = format!("{:p}", &x);  // addressを文字列で取得
    println!("id: x={}", y);
    let z = x;
    println!("id: x is z?: {}", (&z as *const _) == (&x as *const _));
}
```

## input
```rust
fn input() {
    print!("Please input any:");
    let mut x = String::new();
    std::io::stdin().read_line(&mut x).ok().expect("Failed");
    println!("input: {}", x);
}
```

## int
```rust
fn int() {
    let x: i32 = "123".parse().ok().except("not int");
    assert_eq!(x, 123);
    let y = 123.456f32 as i32;
    assert_eq!(x, y);
}
```

## iter
```rust
fn iter() {
    let x = [1, 2];
    let y = x.iter();
}
```

## len
```rust
fn len() {
    let x = [1, 2];
    println!("len: {}", x.len());
}
```

## list
```rust
fn list() {
    // Fixed size
    let x = [1, 2];
    // Variable size
    let mut y = vec![1, 2];
    y.push(3);
}
```

## map
```rust
fn map() {
    let x = [1, 2];
    let y = x.iter().map(|&x| x * 2);
    println!("map: {:?}", y.collect::<Vec<i32>>());
}
```

## max
min_maxはまだunstable

```rust
fn max() {
    let x = [1, 3, 2];
    let y = x.iter().max();
    println!("max: {:?}", y);
    println!("max: min_max: {:?}", x.iter().min_max());
    println!("max: number: {}", std::cmp::max(5, 3));
}
```

## min
min_maxはまだunstable

```rust
fn min() {
    let x = [1, 3, 2];
    let y = x.iter().min();
    println!("min: {:?}", y);
    // println!("min: min_max: {:?}", x.iter().min_max());
    println!("min: number: {}", std::cmp::min(5, 3));
}
```

## next
```rust
fn next() {
    let x = [1, 2, 3];
    let mut y = x.iter();
    println!("next: {:?}", y.next());  // iterator自体をmutableにする必要あり
    println!("next: {:?}", y.next());
}
```

## oct
```rust
fn oct() {
    let x = format!("{:o}", 10);
    println!("oct: {}", x);
}
```

## open
```rust
fn open() {
    let x = std::fs::File::open("hoge.txt");
}
```

## ord
```rust
fn ord() {
    // castすると得られる
    let x = 'あ' as u32;
    println!("ord: 0x{:x}, {}", x, x);
}
```

## pow
```rust
fn pow() {
    use std::num::{Int, Float};
    println!("pow: {}", 2.pow(3));
    println!("powf: {}, powi: {}", 2.0f32.powf(3.0f32), 2.0f32.powi(-1));
}
```

## print
```rust
fn print() {
    print!("print!");
    println!("println!");
}
```

## range
range notationを使う。step_byによる飛び飛びのrangeはまだunstable

```rust
fn _range() {
    println!("range: {:?}", (0..2).collect::<Vec<i32>>());
    // unstable
    // println!("range_step: {:?}", (0..4).step_by(2).collect::<Vec<i32>>());
    // println!("range_step(negative): {:?}", (4..0).step_by(-2).collect::<Vec<i32>>());
```

## reverse
```rust
fn reverse() {
    let x = [1, 2];
    for i in x.iter().rev() {println!("reverse: {}", i);}  // reverse iterator
    let mut y = x.clone();
    y.reverse();  // 直接逆順にする
}
```

## round
```rust
fn round() {
    // Pythonのroundとは挙動が違う
    use std::num::Float;
    println!("round 0.5 = {}", 0.5f32.round());
    println!("round -0.5 = {}", -0.5f32.round());
    println!("round 1.5 = {}", 1.5f32.round());
    println!("round -1.5 = {}", -1.5f32.round());
}
```


## slice
slice notationに一本化される見通し？
閉区間は作れなくなった。今後どうなるのかな？

```rust
fn slice() {
    let x = [1, 2, 3, 4, 5];
    println!("slice of {:?}: {:?}", x, &x[1..3]);
    println!("slice_from of {:?}: {:?}", x, &x[1..]);
    println!("slice_to of {:?}: {:?}", x, &x[..3]);
    println!("full_slice of {:?}: {:?}", x, &x[..]);
}
```

## sorted
```rust
fn sorted() {
    // in-placeのみ
    let x = [1, 4, 2, 3];
    let mut y = x.clone();
    y.sort();
    println!("sort: {:?}", y);
}
```

## sum
ズバリsum()はまだunstableなので、foldで代用する

```rust
fn sum() {
    let x = (1..11).fold(0, |n, x| n + x);
    println!("sum from 1 to 10 = {}", x);
    // unstable
    // println!("sum: {}", (1..11).sum::<i32>());
}
```

## super
Rustのsuperキーワードは、親モジュールを指す為に用いられる

```rust
use super::child_module;
```

## tuple
```rust
fn tuple() {
    let x = (1, "string");
}
```

## type

std::intrinsicsにあるのか？よくわからん

## zip
```rust
fn zip() {
    let x = [1, 2];
    let y = ["one", "two"];
    // ３つ以上の要素を気軽にまとめるのは無理っぽい。自分でflat_map使って関数書けば出来る
    let z: Vec<(&i32, &&str)> = x.iter().zip(y.iter()).collect();
    println!("{:?}", z);
}