如何在Haskell中正确使用toLower?

问题描述 投票:0回答:2

我最近开始学习 Haskell,想将一些内容转换为小写。我查了“toLower”函数,但似乎不起作用。

Prelude> import Data.Text
Prelude Data.Text> toLower "JhELlo"

<interactive>:2:9: error:
    * Couldn't match expected type `Text' with actual type `[Char]'
    * In the first argument of `toLower', namely `"JhELlo"'
      In the expression: toLower "JhELlo"
      In an equation for `it': it = toLower "JhELlo"
Prelude Data.Text> toLower 'JhELlo'

<interactive>:3:9: error:
    * Syntax error on 'JhELlo'
      Perhaps you intended to use TemplateHaskell or TemplateHaskellQuotes
    * In the Template Haskell quotation 'JhELlo'
Prelude Data.Text>
haskell
2个回答
16
投票

它不起作用,因为您尝试使用的版本在

Text
上运行,而不是在
String
上运行。这是两种不同的类型。此时您有两个选择:

1) 使用

toLower
中的
Data.Char
;这个对单个字符进行操作,您可以将其映射到您的字符串上:

map toLower "JhELlo"

2) 将字符串转换为

Data.Text
(也可以选择再次转换回来):

unpack . toLower . pack $ "JhELlo"

实际上还有其他版本的

toLower
Data.Sequences
中的那个似乎是多态的(因此应该对两者都有效),但它可能需要将
mono-traversable
包作为依赖项拉入。


© www.soinside.com 2019 - 2024. All rights reserved.