简体   繁体   English

Haskell从字符串中获取字符数组?

[英]Haskell get character array from string?

如果给出一个字符串,我可以让每个字符组成该字符串吗?

In Haskell, strings are just (liked) lists of characters; 在Haskell中,字符串只是(喜欢)字符列表; you can find the line 你可以找到这条线

type String = [Char]

somewhere in the source of every Haskell implementation. 在每个Haskell实现的源代码中的某个地方。 That makes tasks such as finding the first occurence of a certain character ( elemIndex 'a' mystring ) or calculating the frequency of each character ( map (head &&& length) . group . sort ) trivial. 这使得诸如找到某个字符的第一个出现( elemIndex 'a' mystring )或计算每个字符的频率( map (head &&& length) . group . sort elemIndex 'a' mystring )这样的任务是微不足道的。

Because of this, you can use the usual syntax for lists with strings, too. 因此,您也可以使用带字符串的列表的常用语法。 Actually, "foo" is just sugar for ['f','o','o'] , which in turn is just sugar for 'f' : 'o' : 'o' : [] . 实际上, "foo"只是['f','o','o']糖,而这只是'f' : 'o' : 'o' : []'f' : 'o' : 'o' : [] You can pattern match, map and fold on them as you like. 您可以根据需要对它们进行模式匹配,贴图和折叠。 For instance, if you want to get the element at position n of mystring , you could use mystring !! n 例如,如果你想获得mystring位置n的元素,你可以使用mystring !! n mystring !! n , provided that 0 <= n < length mystring . mystring !! n ,假设0 <= n < length mystring

Well, the question does say he wants an array: 好吧,问题确实说他想要一个数组:

import Data.Array
stringToArray :: String -> Array
stringToArray s = listArray (0, length s - 1) s

The string type is just an alias for [Char] so you don't need to do anything. string类型只是[Char]别名 ,因此您无需执行任何操作。

Prelude> tail "Hello"
"ello"
Prelude> ['H', 'e', 'l', 'l', 'o']
"Hello"
Prelude> "Hello" !! 4
'o'

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

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