Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?

More than 1 year has passed since last update.

@maueki

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

ここで紹介されている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
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
0
Help us understand the problem. What is going on with this article?