31
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2015-01-08

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

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

abs

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

all

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

any

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

ascii

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

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

bin

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

bytearray, bytes

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

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

dict

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

divmod

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

enumerate

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

filter

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

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

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

frozenset, set

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

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

hex

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

id

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

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

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

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

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

len

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

list

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

map

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

max

min_maxはまだunstable

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

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

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

oct

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

open

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

ord

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

pow

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

fn print() {
    print!("print!");
    println!("println!");
}

range

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

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

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

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に一本化される見通し?
閉区間は作れなくなった。今後どうなるのかな?

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

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

sum

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

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キーワードは、親モジュールを指す為に用いられる

use super::child_module;

tuple

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

type

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

zip

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

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
31
22

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?