Creating 2 dimensional list matrix

后端 未结 3 748
迷失自我
迷失自我 2021-01-24 17:07

How do you create a list-based matrix of 1\'s with given row and column counts? For example, like:

row=3,column=4 -> [[1,1,1,1],[1,1,1,1],[1,1,1         


        
相关标签:
3条回答
  • 2021-01-24 17:43

    Here's an alternative method using list comprehension. Let's have a look at the basics:

    Prelude> [ 2*x | x <- [1..4] ]
    [2,4,6,8]
    

    So that gives you one number for each element in the list [1..4]. Why not, instead of doubling x, just have a 1:

    Prelude> [ 1 | x <- [1..4] ]
    [1,1,1,1]
    

    And if we want three of them, we can pull the same trick:

    Prelude> [ [1|x<-[1..4]] | x<-[1..3] ]
    [[1,1,1,1],[1,1,1,1],[1,1,1,1]]
    

    Thus we can define

    twoDlist r c = [ [1|x<-[1..c]] | x<-[1..r] ]
    

    which gives

    Prelude> twoDlist 3 4
    [[1,1,1,1],[1,1,1,1],[1,1,1,1]]
    
    0 讨论(0)
  • 2021-01-24 17:53
    import Control.Applicative
    import Data.Functor 
    
    matrix r c = [1] <* [1..c] <$ [1..r]
    
    0 讨论(0)
  • 2021-01-24 18:01

    You can do this with replicate:

    onesMatrix rows cols = replicate rows (replicate cols 1)
    
    0 讨论(0)
提交回复
热议问题