Haskell隐式转换 [英] Haskell implicit conversions
问题描述
你好,我一直想使用 Data.Text.intercalate
,并且从 Hackage
中我不明白为什么该方法具有以下签名:
Hello i was looking to using Data.Text.intercalate
and from Hackage
i do not understand why if the method has the following signature:
intercalate ::文本->[文字]->文字
为什么可以正常工作
T.intercalate "NI!" ["We", "seek", "the", "Holy", "Grail"]
"WeNI!seekNI!theNI!HolyNI!Grail"
您不应该在列表的每个元素之前应用 Data.Text.pack
吗?
来源: http://hackage.haskell.org/package/text-1.2.3.1/docs/Data-Text.html
就我而言,我想打包以下内容:
Shouldn't you apply Data.Text.pack
it before each element of the list?
Source : http://hackage.haskell.org/package/text-1.2.3.1/docs/Data-Text.html
In my case i want to pack the following :
输入:"{"
, mytext
,}"
#mytext :: Text
我正在使用: Prelude.intercalate(Data.Text.pack,")[pack"{",mytext,pack}"]
或
(pack"{")++ mytext ++包}")
有人可以解释一下为什么 Data.Text
公开与 Data.List
相同的方法(在我们的示例中为 intercalate
)以及如何进行解释.它会在 Char
和 Text
之间进行隐式转换吗?
Input :"{"
,mytext
,"}"
#mytext::Text
I am doing it with :
Prelude.intercalate (Data.Text.pack ",") [pack "{",mytext, pack "}"]
or
(pack "{") ++ mytext++ pack "}")
Can someone please explain me why does Data.Text
expose the same methods as Data.List
(in our case intercalate
) and how does it make implicit conversions between Char
and Text
?
推荐答案
您可能启用了 -XOverloadedStrings
(或通过 {-#LANGUAGE OverloadedStrings#-}
启用了它)在文件顶部).
You likely enabled -XOverloadedStrings
(or enabled it with the {-# LANGUAGE OverloadedStrings #-}
at the top of the file).
As a result this means that string literals (not string variables, only the literals), can be interpreted by any IsString
type.
文本
是 IsString
类型.因此,这意味着您隐式地在字符串 literals 周围使用了 pack
(再次是文字,而不是普通变量).
Text
is an IsString
type. So that means that implicitly you use pack
around the string literals (again literals, not ordinary variables).
数字文字也会发生类似的情况:数字文字可以是任何 Num
类型.根据您在数字文字上调用的函数,Haskell可以得出确切的类型,从而相应地解释"文字.例如,如果您编写 atan2 1 2
,则应将 1
和 2
解释为 RealFloat
类型,而对于 quot 1 2
, 1
和 2
被解释为整数"类型.
A similar thing happens with number literals: a number literal can be any Num
type. Based on what functions you call on the number literal, Haskell can derive the exact type, and thus "interprets" the literal accordingly. For example if you write atan2 1 2
, then 1
and 2
should be interpreted as RealFloat
types, whereas for quot 1 2
, the 1
and 2
are interpreted as Ìntegral` types.
这篇关于Haskell隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!