I am trying to return the length of a list as an Integer
type, but applying length xs
returns the length as an Int
type. How can I work around this issue?
This is what I am trying to achieve: (it does not work)
sizeList :: [Integer] -> Integer
sizeList xs = length xs
It works as soon as I change the return to sizeList :: [Integer] -> Int
but I don't want to do so.
Overview. A string is a list of characters in Haskell. We can get the length of the string using the length function.
Here are two ways to implement Haskell's length function. One way is to map all the elements to 1, then sum them all up. Another way is to add up each head as you recursively call len' with the tail. The result will be the length of the list.
What's the difference between Integer and Int ? Integer can represent arbitrarily large integers, up to using all of the storage on your machine. Int can only represent integers in a finite range. The language standard only guarantees a range of -229 to (229 - 1).
It states that this function is of type Int -> Int , that is to say, it takes an integer as its argument and it returns an integer as its value.
You can either call genericLength
from Data.List
, or call length
and use fromIntegral
to convert the result.
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