LoginSignup
0
0

More than 5 years have passed since last update.

[Rust]HKTに対して関数定義

Last updated at Posted at 2019-04-14

ここで紹介されているHKTに対して関数を定義したい。
具体的には中身の数値(ここではi32)を2乗する関数squareを定義したい。

trait HKT<U> {
    type T;
    type MU;
}

trait Mappable<U>: HKT<U> {
    fn map<F: FnOnce(Self::T) -> U>(self, f: F) -> Self::MU;
}

fn square<T>(mappable: T) -> T::MU
where
    T: Mappable<i32, T = i32>,
{
    mappable.map(|x| x * x)
}

これで完成。Mappableに対してT=i32の型パラメータ指定ができることに気づくまでに時間がかかった。

例えばOptionに対して実装するならこうなる。

impl<T, U> HKT<U> for Option<T> {
    type T = T;
    type MU = Option<U>;
}

impl<T, U> Mappable<U> for Option<T> {
    fn map<F: FnOnce(Self::T) -> U>(self, f: F) -> Self::MU {
        match self {
            Some(v) => Some(f(v)),
            None => None,
        }
    }
}

fn main() {
    let a = Some(1i32);

    println!("{:?}", square(a));
}
0
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
0
0