knkill_prfl
knkill_prfl

Reputation: 217

haskell and string length

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

Upvotes: 10

Views: 21345

Answers (1)

C. A. McCann
C. A. McCann

Reputation: 77384

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.

Upvotes: 14

Related Questions