如何获取文字类型? [英] How to get the text type?
问题描述
我有以下代码
{-# LANGUAGE OverloadedStrings, TypeSynonymInstances, FlexibleInstances #-}
module Lib where
import Data.Text (Text)
class DoSomething a where
something :: a -> IO ()
instance DoSomething String where
something _ = putStrLn "String"
instance DoSomething Text where
something _ = putStrLn "Text"
在REPL中,我尝试获取 Text
类型的实例,如下所示:
And in REPL, I tried to get an instance of Text
type as the following:
:t something ("hello" :: Text)
编译器抱怨:
<interactive>:1:12: error:
• Couldn't match expected type ‘Text’ with actual type ‘[Char]’
• In the first argument of ‘something’, namely ‘("hello" :: Text)’
In the expression: something ("hello" :: Text)
默认情况下,它将采用 String
类型:
By default, it will take the String
type :
:t something "hello"
something "hello" :: IO ()
如何获取 Text
类型而不是 String
类型?
How to get Text
type instead of String
type?
推荐答案
您的代码没有任何问题.做这样的事情本身会导致这样的错误:
There is nothing problematic with your code. Doing something like this itself would result in such an error:
λ> import Data.Text
λ> let t = "hello world" :: Text
<interactive>:11:9: error:
• Couldn't match expected type ‘Text’ with actual type ‘[Char]’
• In the expression: "hello world" :: Text
In an equation for ‘t’: t = "hello world" :: Text
但是您可以使用 String
:
λ> let t = "hello world" :: String
请注意,即使文件中具有 OverloadedString
扩展名,当您在repl中加载该文件时也不会加载该文件.您可以看到当前正在加载的扩展名,如下所示:
Note that even though your file has OverloadedString
extension in it, it won't be loaded when you load that file in the repl. You can see the currently loaded extensions like this:
λ> :show language
base language is: Haskell2010
with the following modifiers:
-XNoDatatypeContexts
-XNondecreasingIndentation
您可以使用 OverloadedStrings
扩展名将其注释为 Text
甚至是 ByteString
.
You can use the OverloadedStrings
extension to annotate it to Text
or even ByteString
.
λ> :set -XOverloadedStrings
λ> :show language
base language is: Haskell2010
with the following modifiers:
-XNoDatatypeContexts
-XNondecreasingIndentation
-XOverloadedStrings
λ> let t = "hello" :: Text
λ> import Data.ByteString
λ> let t = "hello" :: ByteString
在repl中设置上述扩展名后,您的代码将起作用:
With the above extension set in repl, your code will work:
λ> :t something ("hello" :: Text)
something ("hello" :: Text) :: IO ()
λ> something ("hello" :: Text)
Text
OverloadedStrings扩展增加了对重载字符串的支持.您可以在此处.简短说明:通过将类型定义为 IsString
类型类的实例,可以通过String文字来表示它:
The OverloadedStrings extension adds support for overloaded strings. You can find more detabils about it here. Short explanation of it: By definining your type to be an instance of IsString
typeclass, you can denote it via String literal:
import GHC.Exts (IsString(..))
data MyFancyText =
MyFancyText String
deriving (Show, Eq, Ord)
instance IsString MyFancyText where
fromString str = MyFancyText str
然后在REPL中:
λ> let xs = "hello" :: MyFancyText
λ> :t xs
xs :: MyFancyText
这篇关于如何获取文字类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!