Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double exclamation marks in Haskell

Tags:

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.
like image 817
BufBills Avatar asked Jun 26 '14 03:06

BufBills


2 Answers

!! 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 ⊥.

like image 176
icktoofay Avatar answered Oct 19 '22 21:10

icktoofay


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.

like image 30
Charlie Lidbury Avatar answered Oct 19 '22 19:10

Charlie Lidbury