Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Index of current element in Haskell list comprehension

Is there any way that I can know the index of current element that x is pointing to in the code below:

funcName k = [<current_index_here> | x <- list, x == k]

Any help would be greatly appreciated.. Thanks :)

like image 887
Swapnil B. Avatar asked Mar 07 '18 05:03

Swapnil B.


People also ask

How list comprehension works in haskell?

List comprehension in Haskell is a way to produce the list of new elements from the generator we have passed inside it. Also for the generator values, we can apply the Haskell functions to modify it later. This list comprehension is very y easy to use and handle for developers and beginners as well.

Does Haskell support list comprehension?

The specification of list comprehensions is given in The Haskell 98 Report: 3.11 List Comprehensions. The GHC compiler supports parallel list comprehensions as an extension; see GHC 8.10. 1 User's Guide 9.3. 13.

Is Haskell 0 indexed?

Indexes are zero based, so [1,2,3] !! 0 will result in 1 .


2 Answers

Index each element with an integer using zip:

funcName k = [if i == 2 then ... else ... | (i,x) <- zip [0..] list, x == k]
like image 170
arrowd Avatar answered Oct 21 '22 21:10

arrowd


Maybe like this with the ilist library (a very useful library):

import Data.List.Index 
> indexed [i*i | i <- [7,6,5]]
[(0,49),(1,36),(2,25)]

Not sure it's exactly what you want but that should be close I believe.

like image 40
Stéphane Laurent Avatar answered Oct 21 '22 20:10

Stéphane Laurent