Understanding Haskell List 0 and 1

I am trying to write a function

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

which returns a list of nintegers, all 0', except for the vth element that should be 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 have great difficulty with this. In particular, I cannot figure out how to do the repetition 0. I understand the concept of building a list from let say [1..n], but I just get[1,2,3,4,5]

Any help with this would be greatly appreciated. Thank.

+5
source share
8 answers

Try:

let row n v = map (\x -> if x == v then 1 else 0) [1..n]
+16
source

Here's the "monadic" solution:

row n v = [(v-1, 0), (1, 1), (n-v, 0)] >>= (uncurry replicate)

replicate , . replicate (v-1) 0 v-1. uncurry replicate, . >>= - ; concatMap .

+11

:

 row n v = [if x == v then 1 else 0 | x <- [1..n]]

fromEnum ( dave4420)

 row n v = [fromEnum (x == v) | x <- [1..n]]
+8

:

row n v = replicate (v-10 ++ [1] ++ repl­icate (n-v)­ 0
+3

, :

row :: Int -> Int -> [Int]
row 0 _ = []
row n 1 = 1 : (row (n-1) 0)
row n m = 0 : (row (n-1) (m-1))

, "" :

row :: Int -> Int -> [Int]
row 0 _ = []
row n m = take (m - 1) zeros ++ [1] ++ take (n - m) zeros
    where zeros = (iterate id 0)
+1

c lst. c , lst - , .

row :: Int -> Int -> [ Int ]
row 0 0 = []
row n v = rowHelp n v 1 [] where
    rowHelp n v c lst
            | c > n = lst
            | v == c = rowHelp n v ( c + 1 ) ( lst ++ [ 1 ] )
            | otherwise = rowHelp n v ( c + 1 ) ( lst ++ [ 0 ] )

~
~

0

haskell , , . :

row n v = [if (x `mod` v==0) then 1 else 0  | x <- [1..n] ]

1,2 n. , v, , 1 , 0.

:

> row 0 0
[]
> row 5 1
[1,0,0,0,0]
> row 5 3
[0,0,1,0,0]
> row 15 3
[0,0,1,0,0,1,0,0,1,0,0,1,0,0,1]

HTH Chris

0

, :

row n v = result           
    where
        result = take n numbers        -- our result will have a length of n
        numbers = map trans [1,2,..]   -- and is some transformation of
                                       -- the list of natural numbers
        trans e
           | e `mod` v == 0  = 1       -- let every v-th element be 1
           | otherwise       = 0       -- 0 otherwise

, , row n v, , . Sartre , , .

0

All Articles