1
votes

I'm new to Haskell and coding in general and am having a bit of a problem.

sti :: [Char] -> [Integer]
sti "" = [fromIntegral (ord x)| x<-""]

So what I am trying to do with the above is create a list of integers from a string, for example "Hello" becomes ['H','e','l','l','o'] and then I turn that list into their respective ord values from Data.Char.

My problem is that when I try to use this function I get: Non-exhaustive patterns in function sti. Does this mean there are instances where I can't take the ord x of a string? And if so how would I go about fixing that?

Anything help would be appreciated.

2
"" is an empty string, you need a variable instead. This question lacks minimal understanding of the problem. I suggest, you first visit www.learnyouahaskell.com - Nikita Volkov
Or, once you understand this version, you could use sti = fmap (fromIntegral . ord) - Rein Henrichs

2 Answers

2
votes

You're only handling the case of the empty string, "". You want this:

sti :: [Char] -> [Integer]
sti xs = [fromIntegral (ord x) | x <- xs]

xs is a variable and will match anything, which is what you want in this case.

Note that you can use pattern-matching to implement special cases, e.g.:

sti :: [Char] -> [Integer]
sti "" = [1,2,3]
sti xs = [fromIntegral (ord x) | x <- xs]

This function returns the ASCII character values of the characters in the input string, except when the input is the empty string, in which case it returns [1,2,3] instead. This can be a useful feature even if it's not what you want here.

If you only implement special cases, and leave cases for which you have defined no value for your function, you'll crash if you try to evaluate your function for those cases:

Prelude Data.Char> let sti "" = [fromIntegral (ord x) | x <- ""]
Prelude Data.Char> sti "foo"
*** Exception: <interactive>:9:5-45: Non-exhaustive patterns in function sti
1
votes

You're using "" as if it were a variable name. But in Haskell, it stands for empty string instead. So your function is only defined for empty strings, and will give you the non-exhaustive pattern error in all other cases.

You ought to replace that with a proper variable name.