[Haskell] Haskell [x] and x notation - as-pattern example
Daniel Frumin
difrumin at gmail.com
Wed Apr 3 14:30:00 CEST 2013
> Also xs is of what type? list of values? So does this mean x is an element and xs must be of type list
Exactly.
x is of type Char and xs is of type [Char].
The list concatenation function (++) expects both of its arguments to be lists, so that's the reason you need to turn a Char x into a list containing only one value ([x]).
—
Sincerely yours,
Daniil Frumin
Angus Comber <anguscomber at gmail.com="mailto:anguscomber at gmail.com">> wrote:
I am reading Learn you a Haskell for great good and on page 40 - as-patterns.
I have changed the example slightly to be:
firstLetter :: String -> String
firstLetter "" = "Empty string, oops"
firstLetter all@(x:xs) = "The first letter of " ++ all ++ " is " ++ [x] ++ " otherbit " ++ xs
Then can use like this:
*Main> firstLetter "Qwerty"
"The first letter of Qwerty is Q otherbit werty"
But I was confused about the difference between [x] and x and why I have to use [x] in the above example.
For example if I change to
firstLetter :: String -> String
firstLetter "" = "Empty string, oops"
firstLetter all@(x:xs) = "The first letter of " ++ all ++ " is " ++ x ++ " otherbit " ++ xs
I get error:
Couldn't match expected type `[Char]' with actual type `Char'
In the first argument of `(++)', namely `x'
In the second argument of `(++)', namely `x ++ " otherbit " ++ xs'
In the second argument of `(++)', namely
`" is " ++ x ++ " otherbit " ++ xs'
I can use xs to print "werty" but have to use [x] to print "Q". Why is that?
What does [x] mean?
In the (x:xs) : just delimits each element. so x is the first element. Why can I not print by using x?
Also xs is of what type? list of values? So does this mean x is an element and xs must be of type list? Confused...
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/haskell/attachments/20130403/9557588e/attachment.htm>
More information about the Haskell
mailing list