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
Overview. A string is a list of characters in Haskell. We can get the length of the string using the length function.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With