Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

haskell and string length

Tags:

haskell

i'm newbie in haskell, and i have question: i write code:

word_list = ["list", "lol", "wordword"]
check str = if head str == 'l' then tail str else str
average wl = (length $ concat $ map check wl) `div` length wl

this code must delete first "l" symbol in every word in word list, concat recieved words, get length of result string and div on words count.

so in this code i must recieve: 13 / 3 = 4,333... ("listlolwordword" = 15, "istolwordword" = 13) but i recieve just 4.

average :: [[Char]] -> Float don't work, i recieve error. where my mistake? ps. sorry my english, please

like image 660
knkill_prfl Avatar asked Jul 14 '11 22:07

knkill_prfl


People also ask

How do I find the length of a string in Haskell?

Overview. A string is a list of characters in Haskell. We can get the length of the string using the length function.

What does length do in Haskell?

length returns the length of a finite list as an Int. It is an instance of the more general genericLength, the result type of which may be any kind of number. O(1) length returns the length of a ByteString as an Int.

What is Haskell take?

Introduction to Haskell take function. We have one function defined in Haskell which is used to take the values from the existing list or it simply takes the value from the existing values available and creates a new list of the variable for us.


1 Answers

The length function returns an Int, and the div function performs integer division, in other words, it drops the fractional part. If you want a Float result, you need to first convert the result of length to a Float, then use (/) for division instead:

word_list = ["list", "lol", "wordword"]
check str = if head str == 'l' then tail str else str
average wl = fromIntegral (length $ concat $ map check wl) / fromIntegral (length wl)

While I'm at it, you should consider using pattern matching in check instead, e.g.:

check ('l':str) = str
check str = str

This style is both more readable and less likely to have mistakes--for example, your version will fail if given an empty string.

like image 131
C. A. McCann Avatar answered Oct 19 '22 10:10

C. A. McCann