从类型'T a`转换为`T b`而不需要样板 [英] Convert from type `T a` to `T b` without boilerplate

查看:146
本文介绍了从类型'T a`转换为`T b`而不需要样板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我有一个AST数据类型,它有大量的情况,这是通过注解类型进行参数化的。

  data Expr a = Plus a Int Int 
| ...
| Times a Int Int

我有注释类型 S T ,还有一些函数 f :: S - > Ť。我想通过我的转换将 Expr S 转换为 Expr T f 对每个 S 发生在Expr值内。



有没有办法使用SYB或泛型来做到这一点,并避免在每种情况下模式匹配?这似乎是这种适合的类型。我只是对SYB不够熟悉,不知道具体的实现方式。 解析方案

听起来你想要一个 Functor 实例。这可以由GHC使用 DeriveFunctor 扩展名自动获得。


So, I have an AST data type with a large number of cases, which is parameterized by an "annotation" type

data Expr a = Plus a Int Int
    | ...
    | Times a Int Int

I have annotation types S and T, and some function f :: S -> T. I want to take an Expr S and convert it to an Expr T using my conversion f on each S which occurs within an Expr value.

Is there a way to do this using SYB or generics and avoid having to pattern match on every case? It seems like the type of thing that this is suited for. I just am not familiar enough with SYB to know the specific way to do it.

解决方案

It sounds like you want a Functor instance. This can be automatically derived by GHC using the DeriveFunctor extension.

这篇关于从类型'T a`转换为`T b`而不需要样板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆