Saturday, 30 April 2016

Haskell: String data type

String is a Collection of characters.


variable.hs
-- String is a collection of characters
str1, str2 :: String
str1 = "Hello, Haskell!"
str2 = "Hello PTR"

*Main> :load variable.hs
[1 of 1] Compiling Main             ( variable.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> str1
"Hello, Haskell!"
*Main> 
*Main> str2
"Hello PTR"
*Main> 
*Main>


In Haskell String is implemented as list of characters internally.
Prelude> let hello = ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
Prelude> hello
"hello world"
Prelude> 
Prelude> :t hello
hello :: [Char]
Prelude> 
Prelude> 'h':'e':'y':' ':hello
"hey hello world"
Prelude> 


You can define string using square brackets (or) by using double quotes "".
Prelude> let str1 = "Hello"
Prelude> let str2 = ['H', 'e', 'l', 'l', 'o']
Prelude> 
Prelude> str1
"Hello"
Prelude> str2
"Hello"
Prelude> 
Prelude> :t str1
str1 :: [Char]
Prelude> :t str2
str2 :: [Char]
Prelude> 
Prelude> str1 == str2
True
Prelude> [1, 2, 3] == [1, 2]
False

Escaping special characters
Escape sequences in programing languages has special meaning, For example, \n prints string in new line, \t is a tab character etc., \ Following tables summarizes some of the escape characters in Haskell.
Escape Character
Description
\0
Null character
\a
Alert
\b
Backspace
\f
Form feed
\n
New line
\r
Carriage return
\t
Horizontal tab
\v
Vertical tab
\"
Double Quote
\&
Empty string
\'
Single Quote
\\
Backslash

*Main> let str1 = "Hello\nWorld"
*Main> 
*Main> putStrLn str1
Hello
World
*Main> 
*Main> let str2 = "Hello, My Name is \"Hari krishna\""
*Main> str2
"Hello, My Name is \"Hari krishna\""
*Main> 
*Main> putStrLn str2
Hello, My Name is "Hari krishna"
*Main>

Multiline String literals
Some times you want to write a string that spans multiple lines, By terminating a line with \, you can create multiline string literals.

sample.hs
quoteOfTheDay = "It is a strange experience, that those who have left me have always \
\left places for a better quality of people. I have \
\never been a loser."

*Main> :load sample.hs
[1 of 1] Compiling Main             ( sample.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> quoteOfTheDay
"It is a strange experience, that those who have left me have always left places for a better quality of people. I have never been a loser."
*Main> 







Previous                                                 Next                                                 Home

No comments:

Post a Comment