简体   繁体   English

在Haskell函数类型声明中使用[Char]而不是String是一个坏主意

[英]Is it a bad idea to use [Char] instead of String in Haskell function type declaration

I have just started learning Haskell using "Learn you a Haskell for Great Good". 我刚刚开始学习Haskell,“学习Haskell for Great Good”。 I am currently reading "Types and Typeclasses" chapter, so my knowledge is pretty .. non-existent. 我目前正在阅读“类型和类型类”一章,所以我的知识非常......不存在。 I am using Sublime Text 2 with SublimeHaskell package which builds/checks file on every save. 我使用Sublime Text 2和SublimeHaskell包,它在每次保存时构建/检查文件。

The problem: I'm trying to make function type declaration like this: 问题:我正在尝试像这样进行函数类型声明:

funcName :: [Char] -> [Char]

I'm getting this warning: 我收到这个警告:

Warning: Use String Found: [Char] -> [Char] Why not: String -> String 警告:使用找到的字符串:[Char] - > [Char]为什么不:String - > String

Build FAILED 建立失败

Can you explain to me why is it a bad idea to use Char array instead of String or give me a link to an explanation of possible repercussions etc. I've googled and found nothing. 你能解释一下为什么使用Char数组而不是字符串是一个坏主意,或者给我一个链接来解释可能的反响等等。我用Google搜索,什么也没发现。

PS I'm a C# developer, I understand the difference between char array and strings in c-like languages. PS我是一名C#开发人员,我理解char数组和c语言中的字符串之间的区别。

Somewhere in the base library you will find this definition: 在基础库的某个地方你会发现这个定义:

type String = [Char]

which says that String and [Char] are exactly the same thing. 它说String[Char]完全是一回事。 Which of the two you choose is a documentation choice. 您选择哪两个是文档选择。 I often define type aliases like this: 我经常定义类型别名,如下所示:

type Domain = ByteString
type UserName = Text

It's a good idea to use types for documentation. 使用文档类型是个好主意。

Also as an important side note, [Char] is not the type for character arrays, but character lists. 另外作为一个重要的注意事项, [Char]不是字符数组的类型,而是字符列表。 Since there are also actual array types, the distinction is important! 由于还有实际的数组类型,区别很重要!

String只不过是[Char]的类型别名,所以两者之间没有实际意义 - 这只是一个可读性的问题。

You seem to be running HLint on your code automatically, and treating any HLint warnings as fatal errors. 您似乎自动在代码上运行HLint,并将任何HLint警告视为致命错误。 As the HLint author says "Do not blindly apply the output of HLint". 正如HLint作者所说: “不要盲目地应用HLint的输出”。 String and [Char] are exactly the same, as everyone says, it's a question of which looks nicer. String[Char]完全相同,正如大家所说,这是一个看起来更好的问题。 I would tend to use String if I'm operating on contiguous lists of characters I want to treat as a block (most of the time), and explicitly use [Char] when the characters don't make sense combined in a run (far rarer). 我倾向于使用String如果我在连续的字符列表上操作,我想将其视为一个块(大多数时候),并且当字符在运行中没有意义时显式使用[Char] (远罕见)。 HLint divides all hints into error (fix) and warning (think), so perhaps it might be best only to build fail on error hints. HLint将所有提示划分为错误(修复)和警告(思考),因此也许最好只在错误提示上构建失败。

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

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