Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

result list of map is one longer [duplicate]

Tags:

haskell

in this Haskell example the result is sometimes one longer than the base list. Any clue for this?

Prelude> let x3 = [1,3..10]
Prelude> x3
[1,3,5,7,9]
Prelude> length x3
5
Prelude> length $ map (+1) x3
5
Prelude> length $ map (*3) x3
5
Prelude> length $ map (/2) x3
6
Prelude> length $ map (/1) x3
6
Prelude> length $ map (`div`1) x3
5
Prelude> map log x3
   [0.0,1.0986122886681098,1.6094379124341003
   ,1.9459101490553132,2.1972245773362196,2.3978952727983707]
Prelude> length it
6
like image 904
Leopold Faschalek Avatar asked Sep 24 '15 19:09

Leopold Faschalek


People also ask

Can a map have duplicate values?

Map does not supports duplicate keys. you can use collection as value against same key. Because if the map previously contained a mapping for the key, the old value is replaced by the specified value.

How can I tell if a map has duplicate keys?

You could do a check using the Map's containsKey() method to see if the key is already present in your Map. A hash map can only store one value for each key. So if you do add another "David" with value 555 it will overwrite the original value.

Which map will allow duplicate keys?

You can use a TreeMap with a custom Comparator in order to treat each key as unequal to the others. It would also preserve the insertion order in your map, just like a LinkedHashMap. So, the net result would be like a LinkedHashMap which allows duplicate keys!


1 Answers

As @duplode suggested, it has to do with how .. behaves with floating point vs. integers:

Prelude> let x3 = [1,3..10] :: [Double]
Prelude> length x3
6
Prelude> let x3 = [1,3..10] :: [Int]
Prelude> length x3
5

Update in response to the comment...

A definition like this in ghci:

let xs = [1,3..11]

is polymorphic. The .. is a shortcut for the enumFromThenTo function:

let xs = enumFromThenTo 1 3 11

The result is polymorphic - the above expression has type:

ghci> :t xs
x3 :: (Enum t, Num t) => [t]

If you just print it out, Haskell chooses to type is as [Integer], and you get:

[1,3,5,7,9]

Here the Integer version of enumFromThenTo is being used.

However, if you apply a floating point operation to the list, Haskell interprets it as [Double], and then it becomes one element longer for the reasons explained above:

ghci> map (+ 0.0) x3
[1.0,3.0,5.0,7.0,9.0,11.0]  -- length 6 now!

So the map operation "changes" the length of the list only because it changes the interpretation of its type which changes which enumFromThenTo function is called to construct it.

Upshot: A list defined like [1,3..11] does not have known length until its type is determined.

like image 164
ErikR Avatar answered Sep 30 '22 09:09

ErikR