gpt4 book ai didi

haskell - OverloadedStrings 语言扩展如何工作?

转载 作者:行者123 更新时间:2023-12-05 08:53:00 24 4
gpt4 key购买 nike

我正在尝试了解页面 https://ocharles.org.uk/posts/2014-12-17-overloaded-strings.html 中的语言扩展 OverloadedStrings .

当启用 OverloadedStrings 时,String 变成类型 Data.String.IsString a => a:

Prelude Data.String> :t fromString "Foo"
fromString "Foo" :: IsString a => a

在描述中,作者提到了以下内容:

By enabling this extension, string literals are now a call to the fromString function, which belongs to the IsString type class.

字符串文字现在是对 fromString 函数的调用 是什么意思?

而且作者还提到:

This polymorphism is extremely powerful, and it allows us to write embedded domain specific languages in Haskell source code, without having to introduce new constructs for otherwise normal values.

无需为其他正常值引入新结构是什么意思?

最佳答案

When the OverloadedStrings is enabled, then String becomes a type Data.String.IsString a => a

不,那是不正确的。 String 仍然是 String。它只对字符串 文字 有影响,对类型为 String 的变量没有影响,并且这些仍然可以Strings.

What does string literals are now a call to the fromString function?

这意味着如果你写一个字符串文字,比如"foo",Haskell 隐含地写成fromString "foo",因此你可以像任何 IsString 对象一样使用它。

what does without having to introduce new constructs for otherwise normal values mean?

这意味着我们可以创建我们自己的类型,我们可以为其编写某种“迷你解析器”,从而在我们的代码中将这些对象写为字符串文字。例如,如果我们创建如下数据类型:

newtype BoolList = BoolList [Bool] deriving Show

然后我们就可以写自己的解析器了

instance IsString BoolList where
fromString = BoolList . map toBool
where toBool '1' = True
toBool _ = False

例如,现在我们可以将 Bool 列表定义为:

myboollist :: BoolList
myboollist = "10110010001"

然后我们得到:

Prelude Data.String> myboollist 
BoolList [True,False,True,True,False,False,True,False,False,False,True]

因此我们在这里写了一个字符串文字 "10110010001",这意味着我们隐含地写了 fromString "10110010001"。由于myboollist的类型是BoolList,所以这里很清楚解析的字符串字面量是什么。

因此,如果某些数据类型很复杂,这会很有用,因为我们需要大量代码来构造一个对象。

由于 fromString 调用被推迟,并且通常不是所有 可能的字符串都映射到该类型的值(这里就是这种情况,尽管是否有争议最好只为 '1' 以外的所有内容填写 False),因此当字符串“无法解析”时,它会在运行时引发错误。

关于haskell - OverloadedStrings 语言扩展如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54843477/

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