Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the length of a list as type Integer instead of Int in Haskell

Tags:

haskell

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.

like image 299
Rumen Hristov Avatar asked Oct 21 '14 07:10

Rumen Hristov


People also ask

Is there a length function in Haskell?

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

How do you use length function in Haskell?

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 is the difference between int and integer in Haskell?

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).

What does int -> int mean Haskell?

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.


1 Answers

You can either call genericLength from Data.List, or call length and use fromIntegral to convert the result.

like image 59
Sebastian Redl Avatar answered Nov 10 '22 04:11

Sebastian Redl