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

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

问题描述

我正在尝试理解 Haskell 中的 Monads,在我无数次代码实验中,我遇到了这个问题:

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

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 ""?

推荐答案

首先说明一下

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 使其单态".这样做的结果是 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 或任何其他单子

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

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

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