Liumx31
Liumx31

Reputation: 1210

Indexing list elements in Haskell

I was looking at @evansb's solution to a homework problem in CIS 194. Basically, the problem asks to double every other element in a list and Evan's solution is this:

-- Exercise 3 -----------------------------------------

-- Double every second number in a list starting on the left.
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther = zipWith
  (\x y -> if x `mod` 2 == 0 then y * 2 else y) [(1::Integer)..]

I am kind of confused about (1::Integer), does 1reference the first index? So in the lambda function x corresponds to the index and y corresponds to the actual element at that index?

Upvotes: 0

Views: 324

Answers (1)

Michael Kohl
Michael Kohl

Reputation: 66867

[(1::Integer)..] is the list of all integers, starting from 1. The ::Integer specifies the type.

For the rest of your question: The elements from [(1::Integer)..] will become the values of x. The list that the function doubleEveryOther will be called with will provide the values for y. So the first list is basically just used as a 1-based index.

Upvotes: 5

Related Questions