Strings
Strings are essentially lists of (Unicode) characters and therefore many functions that operate
on lists can also be used with strings:
(+) :: Additive a => a -> a -> a (Prelude)
Adds two objects (numbers, vectors, strings, etc.) together.
sum :: Additive a => [a] -> a (Prelude)
Sum of the elements:
sum [e1,e2,...,eN] = e1 + e2 + ... + eN
Implemented usually more efficiently than with repetitive
application of (+).
length :: Sequence a => a -> Integer (Prelude)
take :: Sequence a => Integer -> a -> a (Prelude)
take n s returns the first n elements of the sequence s.
drop :: Sequence a => Integer -> a -> a (Prelude)
drop n s removes the first n elements of the sequence s.
sub :: Sequence a => a -> Integer -> Integer -> a (Prelude)
sub s begin end returns a subsequence of s starting from
index begin and ending just before index end.
Strings have currently their own function for accessing individual characters
(but in the future they may also support the ! operator):
charAt :: String -> Integer -> Character (Prelude)
charAt string i returns the ith character of the string.
String literals
Single-line strings are enclosed in double quotes and support the following escape sequences:
| Escape |
Meaning |
\n |
Line feed |
\t |
Tab |
\r |
Carriage return |
\uXXXX |
Unicode code point |
\\ |
Literal backslash |
\" |
Literal double quote |
Multi-line strings are enclosed in triple double quotes """...""". Inside triple-quoted
strings no escape processing occurs — backslashes and quotes appear literally:
path = """C:\Users\Alice\Documents\report.txt"""
multiLine = """Line one
Line two
Line three"""
String interpolation
Inside a single-line string, \(expr) embeds the result of expr (converted with show)
directly into the string. This is the preferred way to build strings from dynamic values:
name = "world"
greeting = "Hello, \(name)!" -- "Hello, world!"
radius = 5.0
msg = "Area = \(pi * radius * radius)" -- "Area = 78.53981..."
Interpolation is not available inside triple-quoted strings.
Converting to and from strings
show converts any value whose type has a Show instance to a human-readable string:
show 42 -- "42"
show 3.14 -- "3.14"
show [1,2,3] -- "[1, 2, 3]"
show True -- "True"
read parses a string back to a value (limited to basic types — Integer, Double,
Boolean, etc.):
read "42" :: Integer -- 42
read "3.14" :: Double -- 3.14
To make a custom data type printable with show, derive the Show instance:
data Color = Red | Green | Blue
deriving instance Show Color
show Red -- "Red"
Common string utilities
trim :: String -> String (Prelude)
Removes leading and trailing whitespace from the string.
splitString :: String -> String -> [String] (Prelude)
splitString text pattern splits the string into a list of string where the parts are sepratated in the original list by the given pattern.
replaceString :: String -> String -> String -> String (Prelude)
replaceString original pattern replacement replaces all occurrences of pattern in the string by replacement.
indexOf :: String -> String -> Integer (Prelude)
indexOf string s finds the first occurrence of s from string and returns its index.
If the s does not occur in the string, return -1."
toUpperCase :: String -> String (Prelude)
Converts all letters of the string to upper case.
toLowerCase :: String -> String (Prelude)
Converts all letters of the string to lower case.
intercalate :: String -> [String] -> String (Prelude)
The intercalate function takes a String and a list of Strings
and concatenates the list after interspersing the first argument
between each element of the list.
See also more generic joinWithSeparator
which escapes its arguments using show.
regionMatches :: String -> Integer -> String -> Integer -> Integer -> Boolean (Prelude)
regionMatches str1 offset1 str2 offset2 len tests whether
sub str1 offset1 (offset1+len) == sub str2 offset2 (offset2+len).
intercalate joins a list of strings with a separator:
intercalate ", " ["a", "b", "c"] -- "a, b, c"
StringBuilder
For performance-critical string construction (e.g. assembling large outputs in a loop),
use the StringBuilder module instead of repeated + concatenation:
import "StringBuilder"
result = do
sb = StringBuilder.new
for items $ \item ->
sb << show item << "\n"
StringBuilder.toString sb
Building a string with + inside a loop is O(n²) because each concatenation copies the
accumulated string. StringBuilder gives O(n) performance.
Regular expressions
The String module provides regular expression support based on java.util.regex:
import "String"
pat = compile "[0-9]+" -- compile a pattern
m = matcher pat "abc123def"
if matches m
then print "found digits"
else print "no digits"
-- Replace all matches
result = substituteAll (compile "\\s+") " " "hello world" -- "hello world"
The pattern string uses Java regex syntax.
|