返回类型在块中 [英] Type of return in do block

查看:105
本文介绍了返回类型在块中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I am trying to understand Monads in Haskell and during my countless experiments with code I have encountered this thing:

我试图了解Haskell中的Monads,以及我在无数次实验中遇到过的代码:做
返回da

f2 = do return "da"

以及它不想编译时发生巨大错误关于类型。我认为唯一重要的部分是:

and the fact that it doesnt want to compile with huge error regarding type. I think the only important part is this:

 No instance for (Monad m0) arising from a use of return'
The type variable `m0' is ambiguous  

然后我将代码更改为:

 f2 = do   
 return "da"  :: IO [Char]  

它工作得很好。但是,当我试图搞砸一点,并将类型更改为IO Int时,这又是一个错误。那么为什么这个类型在它实际上不是模糊的时候呢?
另外,当我在返回之前添加一些内容时,如:

And it worked perfectly well. But when I have tried to mess up a bit and change the type to IO Int it was an error once again. So why the type is "ambiguous" when it actually isnt? Also when I will add something before return like:

f2 = do   
  putStrLn "das"  
  return 2

然后我不必指定返回的类型。
那么有人可以解释我究竟发生了什么?为什么在第一种情况下返回输出da?不是没有?

Then I dont have to specify the type of return. So can someone explain me what is going on really? Also why is return outputting "da" in the first case? Not da without ""?

推荐答案

首先让我们指出

First let's just point out that

do
  return a

return a

现在,问题在于 return 的类型为

Now, the problem is that return has the type

return :: Monad m => a -> m a

当您有像

foo = bar

其中 foo 没有参数haskell使它成为monomorphic。这样做的结果是Haskell无法猜测 m 是什么,并且不会推广它,因此您需要显式类型签名。最普遍的是

where foo has no arguments haskell makes it "monomorphic". The result of this is that Haskell can't guess what m is and won't generalize it so you need an explicit type signature. The most general one is

f2 :: Monad m => m String
f2 = return "das"

但是您也可以使用 IO 或任何其他monad

But you could also use IO or any other monad

f2 :: IO String

最后,在你的最后一个例子中,因为你返回 2 ,你'必须给出一个类型签名,表明你正在返回某种数字,比如

Finally, in your last example, since you're returning 2, you'd have to give a type signature that indicates you're returning some sort of number, like

 f2 :: IO Integer

这篇关于返回类型在块中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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