OverloadedStrings
字符串的重載[1]。
Haskell中存在多種表示字符串的類(lèi)型本今,String
算是最常用的了拆座,String
功能卻十分單一,對(duì)于更多需求的功能冠息,往往會(huì)使用其它結(jié)構(gòu)挪凑。
這個(gè)擴(kuò)展體現(xiàn)在“重載”上面。我們來(lái)看一段C++代碼逛艰。
// STL提供的string
std::string s = "hello";
// Qt提供的string
QString s = "hello";
我們把hello
字面量重載成了不同類(lèi)型躏碳,這個(gè)擴(kuò)展所要做的事跟上面代碼差不多。
幾個(gè)示例
我們先看看一段簡(jiǎn)單的代碼:
text :: String
text = "hello"
這段耳熟能詳散怖,但改成Text
就出錯(cuò)了菇绵。
import qualified Data.Text as T
text :: T.Text
text = "hello"
Code.hs:6:8: error:
? Couldn't match expected type ‘T.Text’ with actual type ‘[Char]’
? In the expression: "hello"
In an equation for ‘text’: text = "hello"
|
6 | text = "hello"
| ^^^^^^^
類(lèi)型不匹配,出錯(cuò)了镇眷。我們加上擴(kuò)展就好了咬最。
{-# LANGUAGE OverloadedStrings #-}
import qualified Data.Text as T
text :: T.Text
text = "hello"
IsString
Text
之所以能直接使用字面量進(jìn)行初始化,這是因?yàn)樗呀?jīng)是IsString
的一個(gè)實(shí)例偏灿。如果把我們自己的類(lèi)型也變成IsString
的一個(gè)實(shí)例丹诀,那么我們也可以直接使用字面量初始化。
import GHC.Exts (IsString(fromString))
import Data.Char (toUpper)
newtype XGString = XGString String
instance IsString XGString where
fromString = XGString . (map toUpper)
instance Show XGString where
show (XGString s) = s
text :: XGString
text = "hello"
IsString
在GHC.Exts
模塊中翁垂,需要手動(dòng)引入铆遭。因?yàn)槭恰爸剌d”,我們對(duì)于字面量的字符串默認(rèn)都轉(zhuǎn)換成大寫(xiě)沿猜,最后text
的輸出值為HELLO
枚荣。
注意事項(xiàng)
字面量的字符串無(wú)法運(yùn)用于一些計(jì)算當(dāng)中。
text :: T.Text -> T.Text
text s = "hello, " ++ s
hello,
會(huì)被視為String
類(lèi)型啼肩,所以要小心注意使用范圍橄妆。