Cookbook/Lists and strings

From HaskellWiki
< Cookbook
Revision as of 13:40, 23 April 2009 by Lenny222 (talk | contribs) (lists and strings)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Since strings are lists of characters, you can use any available list function.

Lists

Combining lists

Problem Solution Examples
combining two strings (++)
"foo" ++ "bar"                  --> "foobar"
combining many strings concat
concat ["foo", "bar", "baz"]    --> "foobarbaz"

Accessing sublists

Problem Solution Examples
accessing the first character head
head "foo bar baz"      --> 'f'
accessing the last character last
last "foo bar baz"      --> 'z'
accessing the character at a given index (!!)
"foo bar baz" !! 4      --> 'b'
accessing the first n characters take
take 3 "foo bar baz"    --> "foo"
accessing the last n characters reverse , take
reverse . take 3 . reverse $ "foobar"    --> "bar"
accessing the n characters starting from index m drop, take
take 4 $ drop 2 "foo bar baz"            --> "o ba"

Splitting lists

Problem Solution Examples
splitting a string into a list of words words
words "foo bar\t baz\n"    --> ["foo","bar","baz"]
splitting a string into two parts splitAt
splitAt 3 "foo bar baz"    --> ("foo"," bar baz")

Strings

Multiline strings

"foo\
\bar"               --> "foobar"

Converting between characters and values

Problem Solution Examples
converting a character to a numeric value ord
import Char
ord 'A'    --> 65
converting a numeric value to a character chr
import Char
chr 99     --> 'c'

Reversing a string by words or characters

Problem Solution Examples
reversing a string by characters reverse
reverse "foo bar baz"                        --> "zab rab oof"
reversing a string by words words, reverse, unwords
unwords $ reverse $ words "foo bar baz"      --> "baz bar foo"
reversing a string by characters by words words, reverse, map, unwords
unwords $ map reverse $ words "foo bar baz"  --> "oof rab zab"

Converting case

Problem Solution Examples
converting a character to upper-case toUpper
import Char
toUpper 'a'            --> "A"
converting a character to lower-case toLower
import Char
toLower 'A'            --> "a"
converting a string to upper-case toUpper, map
import Char
map toUpper "Foo Bar"  --> "FOO BAR"
converting a string to lower-case toLower, map
import Char
map toLower "Foo Bar"  --> "foo bar"

Interpolation

TODO

Performance

For high performance requirements (where you would typically consider C), consider using Data.ByteString.

Unicode

TODO