BufBills
BufBills

Reputation: 8103

Double exclamation marks in Haskell

I have this code:

ghci>let listOfFuns = map (*) [0..]
ghci>(listOfFuns !! 4) 5
20
  1. what does this !! mean?

I saw example about double exclamation like this:

ghci> [1,2,3,4]!!1 
ghci> 2

But it seems don't apply to my question example.

  1. how to understand this function. need explanations.

Upvotes: 36

Views: 30173

Answers (2)

Charlie Lidbury
Charlie Lidbury

Reputation: 121

Might find it easier to think in equivilances

let listOfFuns = map (*) [0..] in (listOfFuns !! 4) 5
== (map (*) [0..] !! 4) 5
== (map (*) [0, 1, 2, ...] !! 4) 5
== ([(0*), (1*), (2*), ...] !! 4) 5
== (4*) 5
== 20

You can see here map (*) [0..] is a [Int → Int], so when you take the 3rd element of it (which is what !! 4 does) you get a function Int → Int. Finally 5 is applied to that function to give you 20.

Upvotes: 2

icktoofay
icktoofay

Reputation: 129001

!! indexes lists. It takes a list and an index, and returns the item at that index. If the index is out of bounds, it returns ⊥.

Upvotes: 63

Related Questions