简体   繁体   English

使用重载字符串

[英]Using Overloaded Strings

OverloadedStrings extension is really very useful, however it has some downsides. OverloadedStrings扩展非常有用,但它有一些缺点。 Consider the following function definition: 请考虑以下函数定义:

someFunction :: ToJSSTring a => a -> IO ()
someFunction = js_function . toJSSTring

In this case when if I want to pass a literal value I have to add a type signature explicitly when OverloadedStrings is enabled: 在这种情况下,如果我想传递一个文字值,我必须在启用OverloadedStrings时显式添加一个类型签名:

someFunction ("This is plain string" :: String)
someFunction ("And this one is Text" :: Data.Text.Text)

The reason for this necessity is quite obvious, I suppose OverloadedStrings was designed to ease the passing of literal values to functions that have strict type signatures, making the developer free from writing pack s everywhere where a Text value is needed. 这种必要性的原因非常明显,我认为OverloadedStrings旨在简化文字值传递给具有严格类型签名的函数,使开发人员无需在需要Text值的地方编写pack

The question is there any way, say, to default all string literals without type signatures to Text , or String ? 问题是,有没有任何方法可以默认所有没有类型签名的字符串文字到TextString Or should I just split my code to general functions (with the ToJSString type constraint) and arbitrary ones, which have strict type signatures for their arguments? 或者我应该将我的代码拆分为一般函数(使用ToJSString类型约束)和任意函数,它们的参数具有严格的类型签名?

You can turn on ExtendedDefaultRules as well ( https://www.fpcomplete.com/user/snoyberg/random-code-snippets/overloadedstrings-defaults ): 您也可以打开ExtendedDefaultRuleshttps://www.fpcomplete.com/user/snoyberg/random-code-snippets/overloadedstrings-defaults ):

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}
import Data.Text (Text, pack)

newtype JSString = JSString Text
    deriving Show

class ToJSString a where
    toJSString :: a -> JSString
instance ToJSString [Char] where
    toJSString = toJSString . pack
instance ToJSString Text where
    toJSString = JSString

someFunction :: ToJSString a => a -> IO ()
someFunction = print . toJSString

main :: IO ()
main = someFunction "Hello World"

EDIT You may also want to add default (Text) to the top of your module to have it use Text instead of String by default. 编辑您可能还希望将default (Text)添加到模块的顶部,以使其默认使用Text而不是String

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM