Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

https://keens.github.io/blog/2017/06/24/jienerikusubenkyoukaihosoku/

ここで紹介されている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));
}
itage
ITAGEは「IT」のAGENCYになることを夢、目標として進化、変化していきます。「It’s It Agency」
http://www.itage.co.jp
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした