Haskell进口有副作用吗? [英] Do Haskell imports have side effects?

查看:79
本文介绍了Haskell进口有副作用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我前段时间编写了一些代码,它使用 OverloadedStrings 从十六进制编码的字符串中创建 ByteString 它使用 base16-bytestring 。这工作得很好,但似乎我并不理解它,以及我认为。



让我完全困惑的是这个。为什么

  { - #LANGUAGE OverloadedStrings# - } 

import Data.ByteString.Base16()
将合格的Data.ByteString导入为B

plaintext =The message:: B.ByteString

main =打印纯文本

编译并运行OK,但如果删除 Data.ByteString.Base16 那么它无法编译(类似于这个问题):

  test.hs:6:13:
(Data.String.IsString B. ByteString)
从字面上产生``'

根据 Haskell Wiki ,像这样的导入仅用于导入typeclasses的实例而没有其他用途,但据我所见,base16字节串的源代码没有定义在任何类型类实例中,只需 encode decode 函数。



如何为代码编译提供 IsString 的必要实例?

解决方案

在Haskell中,typeclass实例总是被导出和导入 - 你不能隐藏它们。这通常被称为开放世界假设。



这意味着类型实例也可以被传输导出:如果您导入带有实例的库,它将被导出

在这种情况下, IsString 实例位于数据中.ByteString.Char8 ,它由 Data.ByteString.Base16 导入。您应该能够用以下方式替换您的导入:

  import Data.ByteString.Char8()

有一个很好的 SO问题,如果您有兴趣,请提供一些关于开放世界假设的信息。


I wrote some code a while ago which uses OverloadedStrings to create ByteStrings from hex-encoded String literals, which it decodes using the functions provided by base16-bytestring. This worked fine, but it seems I didn't understand it as well as I thought.

The thing that has me completely confused is this. Why does

{-# LANGUAGE OverloadedStrings #-}

import Data.ByteString.Base16 ()
import qualified Data.ByteString as B

plaintext = "The message" :: B.ByteString

main = print plaintext

compile and run OK, but if I remove the import for Data.ByteString.Base16 then it fails to compile (similar to this question):

test.hs:6:13:
No instance for (Data.String.IsString B.ByteString)
  arising from the literal `"The message"'

According to the Haskell Wiki, an import like this is "useful for only importing instances of typeclasses and nothing else", but as far as I can see, the base16-bytestring source code doesn't define any typeclass instances, just the encode and decode functions.

How does the import provide the necessary instance of IsString for the code to compile?

解决方案

In Haskell, typeclass instances are always exported and imported--you can't hide them. This is usually referred to as the "open world assumption".

This means that typeclass instances are also exported transitively: if you import a library with an instance, it gets exported from your module as well.

In this case, the IsString instance is in Data.ByteString.Char8, which is imported by Data.ByteString.Base16. You should be able to replace your import with:

import Data.ByteString.Char8 ()

There is a nice SO question giving some information on the open world assumption, if you're interested.

这篇关于Haskell进口有副作用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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