Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell list comprehension 0's and 1's

Tags:

list

haskell

I am trying to write a function

row :: Int -> Int -> [Int]
row n v

that returns a list of n integers, all 0's, except for the vth element, which needs to be a 1.

For instance,

row 0 0 = []
row 5 1 = [1,0,0,0,0]
row 5 3 = [0,0,1,0,0]

I am new to Haskell and having a lot of difficulty with this. In particular I can't figure out how to make it repeat 0's. I understand the concept of building a list from let's say [1..n], but I just get [1,2,3,4,5]

Any help with this would be greatly appreciated. Thank you.

like image 968
Shabu Avatar asked Oct 05 '11 07:10

Shabu


1 Answers

Try:

let row n v = map (\x -> if x == v then 1 else 0) [1..n]
like image 196
jeha Avatar answered Oct 04 '22 20:10

jeha