用函数实现Newtype的Functor实例 [英] Implement Functor Instance for Newtype with Function

查看:93
本文介绍了用函数实现Newtype的Functor实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下 newtype



newtype Bar a = Bar {foo: :Int - > a}



我试着为它定义一个 Functor 实例。

  instance Functor(Bar)其中
fmap g(Bar f)= Bar $ fmap f

我打算映射到 Int - > a 得到 Int - > b - 我认为这是正确的结果类型。



然而,我得到了编译时错误:

 无法使用`Int'匹配'f0 Int'类型
预期类型:Int - > f0 a
实际类型:f0 Int - > f0 a在'($)'的第二个参数中,即`fmap f'
在表达式中:Bar $ fmap f

我怎样才能实现这个 Functor 实例?

解决方案它应该是

 实例Functor Bar其中
fmap g(Bar f)= Bar $ fmap gf

我想你可能错过了 g 。你可以看到 f0 Int - > f0 a 因为 f :: Int - > a so fmap f :: Functor f0 => f0 Int - > f0 a 。由于 g :: a - > b ,你想要 fmap g over f ,这样 fmap gf :: Int - > b


Given the following newtype:

newtype Bar a = Bar { foo :: Int -> a }

I tried to define a Functor instance for it.

instance Functor (Bar) where
    fmap g (Bar f) = Bar $ fmap f 

I intended to map over Int -> a to get Int -> b - I think that's the correct resultant type.

However, I got the compile-time error:

Couldn't match type `f0 Int' with `Int' 
Expected type: Int -> f0 a   
Actual type: f0 Int -> f0 a In the second argument of `($)', namely `fmap f' 
In the expression: Bar $ fmap f

How can I implement this Functor instance?

解决方案

It should be

instance Functor Bar where
    fmap g (Bar f) = Bar $ fmap g f

I think you might have just missed the g. You see f0 Int -> f0 a because f :: Int -> a so fmap f :: Functor f0 => f0 Int -> f0 a. Since g :: a -> b, you want to fmap g over f so that fmap g f :: Int -> b.

这篇关于用函数实现Newtype的Functor实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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