2
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?

More than 3 years have passed since last update.

RustとHaskellのちょっとした違い

Posted at

「すごいHaskell楽しく学ぼう!」が手元にあったので、なんとなくコードを真似てみる。

fn main() {
    // "Learn You a Haskell for Great Good" p.7
    // GHCi> let lostNumbers = [4,8,15,16,23,42] 
    let lost_numbers = vec![4,8,15,16,23,42];
    println!("{:?}", lost_numbers);
    
    // p.8
    // GHCi> [1,2,3,4] ++ [9,10,11,12]
    let ns = [[1,2,3,4],[9,10,11,12]].concat();
    assert_eq!(ns, [1, 2, 3, 4, 9, 10, 11, 12]);
    // たしかに結果は同じだが、Rust版は、「配列の配列」が最初にあることになっているので、元のHaskellコードと少し意味が違う。

    // もとのHaskellコードのイメージに近いのはこちら。
    let mut ns_a = vec![1,2,3,4];
    let mut ns_b = vec![9,10,11,12];
    ns_a.append(&mut ns_b);
    assert_eq!(ns_a, [1,2,3,4, 9,10,11,12]);
    assert_eq!(ns_b, []);

    // p.8
    // GHCi> "hello" ++ " " ++ "world"
    let  str = concat!("hello"," ","world");
    assert_eq!(str, "hello world");
    
    // GHCi> ['w','o'] ++ ['o','t']
    let chars = [['w','o'],['o','t']].concat();
    let mut string = String::new();
    for c in chars {
        string.push(c);
    }
    assert_eq!(string, "woot");
    
    // p.10
    assert_eq!(true, [3,2,1] > [2,1,0]);
    assert_eq!(true, [3,2,1] > [2,10,100]);
    assert_eq!(true, [3,4,2] < [3,4,3]);
    assert_eq!(true, [3,4,2] > [2,4]);// ここだけHaskellと動作が違う。
    assert_eq!(true, [3,4,2] == [3,4,2]);

}

[3,4,2] > [2,4]のところだけ、動作が違う。

 
Standard Error

   Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/main.rs:37:32
   |
37 |     assert_eq!(true, [3,4,2] > [2,4]);// ここだけHaskellと動作が違う。
   |                                ^^^^^ expected an array with a fixed size of 3 elements, found one with 2 elements

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

Haskellでは配列の要素数が違っていても処理するのに対し、Rustは「要素数が違う」ことをコンパイルエラーとする。言語による方針の違いがわかる。

2
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
2
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?