How to avoid "Exception: Prelude.head: empty list"? - Haskell

Good evening everyone, I'm new to haskell. I am trying to summarize a Unicode string value read list and store them in a list, and then sum integers.

 getLetterUnicodeValue :: Char -> Int
 getLetterUnicodeValue l = (ord l) - 64

 unicodeValueList :: String -> [Int]
 unicodeValueList x = getLetterUnicodeValue (head x) : unicodeValueList (tail x)

 total :: [Int] -> Int
 total []     = 0
 total x = (head x) + (total (tail x))

I got an empty list error when the string arrived at the last character, and the sum function cannot successfully execute. Is there a way to stop a function unicodeValueListwhen it comes to its end.

*** Exception: Prelude.head: empty list
+4
source share
2 answers

The surest way to avoid this exception is to not use it head. Instead, you can use pattern matching to get the title and tail of the list:

unicodeValueList (x:xs) = getLetterUnicodeValue x : unicodeValueList xs

total (x:xs) = x + total xs

, x xs , , , .

, , : , , . , , , , ( ).

, , ? , unicode, ? , :

unicodeValueList [] = []

, , . if, , head tail, . , , . head tail, , , - , .

+5

, unicodeValueList

unicodeValueList :: String -> [Int]
unicodeValueList [] = []
unicodeValueList (x:xs) = getLetterUnicodeValue x : unicodeValueList xs

, unicodeValueList = map getLetterUnicodeValue. , head, , - ​​ , .

+2

Source: https://habr.com/ru/post/1656749/


All Articles