gpt4 book ai didi

haskell - 如何获取文本类型?

转载 作者:行者123 更新时间:2023-12-03 12:30:21 25 4
gpt4 key购买 nike

我有以下代码

 {-# 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 的实例。键入如下:
: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类型 :
:t something "hello"
something "hello" :: IO ()

如何获得 Text输入而不是 String类型?

最佳答案

您的代码没有任何问题。做这样的事情本身会导致这样的错误:

λ> 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 中加载该文件时,它不会被加载。您可以像这样看到当前加载的扩展:
λ> :show language
base language is: Haskell2010
with the following modifiers:
-XNoDatatypeContexts
-XNondecreasingIndentation

您可以使用 OverloadedStrings将其注释为 Text 的扩展名甚至 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 中设置上述扩展后,您的代码将起作用:
λ> :t something ("hello" :: Text) 
something ("hello" :: Text) :: IO ()
λ> something ("hello" :: Text)
Text

OverloadedStrings 扩展添加了对重载字符串的支持。你可以找到更多关于它的细节 here .简短说明:通过将您的类型定义为 IsString 的实例typeclass,你可以通过字符串文字来表示它:
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

关于haskell - 如何获取文本类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54824085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com