Storing values in an N x N grid Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)mapM for both keys and values of Data.MapStoring hierarchical data in a databaseCapture the notion of invertible functionsSquare grid collision detectionStoring array inside closureA function determining intervals of values greater than thresholdJavaScript 2D Grid WrapperCreating and storing binary arraysBuilding an interval-based gridStoring computed values in an array

What exactly is a "Meth" in Altered Carbon?

What causes the vertical darker bands in my photo?

Do I really need recursive chmod to restrict access to a folder?

How discoverable are IPv6 addresses and AAAA names by potential attackers?

When were vectors invented?

Why are there no cargo aircraft with "flying wing" design?

What does this icon in iOS Stardew Valley mean?

When a candle burns, why does the top of wick glow if bottom of flame is hottest?

Denied boarding although I have proper visa and documentation. To whom should I make a complaint?

English words in a non-english sci-fi novel

Is the Standard Deduction better than Itemized when both are the same amount?

Can a USB port passively 'listen only'?

Echoing a tail command produces unexpected output?

Using audio cues to encourage good posture

Fundamental Solution of the Pell Equation

What is the logic behind the Maharil's explanation of why we don't say שעשה ניסים on Pesach?

Should I discuss the type of campaign with my players?

What is Arya's weapon design?

What's the meaning of 間時肆拾貳 at a car parking sign

Why did the IBM 650 use bi-quinary?

Extract all GPU name, model and GPU ram

Can an alien society believe that their star system is the universe?

3 doors, three guards, one stone

How to answer "Have you ever been terminated?"



Storing values in an N x N grid



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)mapM for both keys and values of Data.MapStoring hierarchical data in a databaseCapture the notion of invertible functionsSquare grid collision detectionStoring array inside closureA function determining intervals of values greater than thresholdJavaScript 2D Grid WrapperCreating and storing binary arraysBuilding an interval-based gridStoring computed values in an array



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2












$begingroup$


I am trying to write a program to store/display a grid of size N x N with cells containing either a 1 or a 0 in preparation for further computation:



module Board where

import Data.List as List

data CellState = One | Zero deriving (Eq, Ord)

data Cell = Cell cellPos :: (Int, Int), cellState :: CellState deriving (Eq, Ord)

type Board = [Cell]

instance Show CellState where
show One = "1"
show Zero = "0"

instance Show Cell where
show (Cell c x) = show (c,x)

genPositions :: Int -> [(Int, Int)]
genPositions x = [ (a,b) | a <- [0..(x-1)], b <- [0..(x-1)] ]

genCellState :: Int -> CellState
genCellState 0 = Zero
genCellState 1 = One

newBoard :: Int -> [Int] -> Board
newBoard i [x] = [Cell (round $ sqrt(fromIntegral i), round $ sqrt(fromIntegral i)) (genCellState x)]
where positions = genPositions $ round $ sqrt(fromIntegral i)
newBoard i (x : xs) = [Cell (positions!!(i - 1 - length xs)) (genCellState x)] ++ newBoard i xs
where positions = genPositions $ round $ sqrt(fromIntegral i)


What improvements can I make to this, both in terms of good practises and performance? I don't like Board being a list of Cells. I posted this on Stack Overflow by accident (have since deleted it) and someone recommended changing type Board = [Cell] to newtype Board = Board getBoard :: Array (Int,Int) CellState but I'm not too familiar with arrays in Haskell so not sure how this would work exactly. From what I have read they apply a function to the elements in the range [Int..Int] and return a list of tuples with the input and output.










share|improve this question











$endgroup$


















    2












    $begingroup$


    I am trying to write a program to store/display a grid of size N x N with cells containing either a 1 or a 0 in preparation for further computation:



    module Board where

    import Data.List as List

    data CellState = One | Zero deriving (Eq, Ord)

    data Cell = Cell cellPos :: (Int, Int), cellState :: CellState deriving (Eq, Ord)

    type Board = [Cell]

    instance Show CellState where
    show One = "1"
    show Zero = "0"

    instance Show Cell where
    show (Cell c x) = show (c,x)

    genPositions :: Int -> [(Int, Int)]
    genPositions x = [ (a,b) | a <- [0..(x-1)], b <- [0..(x-1)] ]

    genCellState :: Int -> CellState
    genCellState 0 = Zero
    genCellState 1 = One

    newBoard :: Int -> [Int] -> Board
    newBoard i [x] = [Cell (round $ sqrt(fromIntegral i), round $ sqrt(fromIntegral i)) (genCellState x)]
    where positions = genPositions $ round $ sqrt(fromIntegral i)
    newBoard i (x : xs) = [Cell (positions!!(i - 1 - length xs)) (genCellState x)] ++ newBoard i xs
    where positions = genPositions $ round $ sqrt(fromIntegral i)


    What improvements can I make to this, both in terms of good practises and performance? I don't like Board being a list of Cells. I posted this on Stack Overflow by accident (have since deleted it) and someone recommended changing type Board = [Cell] to newtype Board = Board getBoard :: Array (Int,Int) CellState but I'm not too familiar with arrays in Haskell so not sure how this would work exactly. From what I have read they apply a function to the elements in the range [Int..Int] and return a list of tuples with the input and output.










    share|improve this question











    $endgroup$














      2












      2








      2





      $begingroup$


      I am trying to write a program to store/display a grid of size N x N with cells containing either a 1 or a 0 in preparation for further computation:



      module Board where

      import Data.List as List

      data CellState = One | Zero deriving (Eq, Ord)

      data Cell = Cell cellPos :: (Int, Int), cellState :: CellState deriving (Eq, Ord)

      type Board = [Cell]

      instance Show CellState where
      show One = "1"
      show Zero = "0"

      instance Show Cell where
      show (Cell c x) = show (c,x)

      genPositions :: Int -> [(Int, Int)]
      genPositions x = [ (a,b) | a <- [0..(x-1)], b <- [0..(x-1)] ]

      genCellState :: Int -> CellState
      genCellState 0 = Zero
      genCellState 1 = One

      newBoard :: Int -> [Int] -> Board
      newBoard i [x] = [Cell (round $ sqrt(fromIntegral i), round $ sqrt(fromIntegral i)) (genCellState x)]
      where positions = genPositions $ round $ sqrt(fromIntegral i)
      newBoard i (x : xs) = [Cell (positions!!(i - 1 - length xs)) (genCellState x)] ++ newBoard i xs
      where positions = genPositions $ round $ sqrt(fromIntegral i)


      What improvements can I make to this, both in terms of good practises and performance? I don't like Board being a list of Cells. I posted this on Stack Overflow by accident (have since deleted it) and someone recommended changing type Board = [Cell] to newtype Board = Board getBoard :: Array (Int,Int) CellState but I'm not too familiar with arrays in Haskell so not sure how this would work exactly. From what I have read they apply a function to the elements in the range [Int..Int] and return a list of tuples with the input and output.










      share|improve this question











      $endgroup$




      I am trying to write a program to store/display a grid of size N x N with cells containing either a 1 or a 0 in preparation for further computation:



      module Board where

      import Data.List as List

      data CellState = One | Zero deriving (Eq, Ord)

      data Cell = Cell cellPos :: (Int, Int), cellState :: CellState deriving (Eq, Ord)

      type Board = [Cell]

      instance Show CellState where
      show One = "1"
      show Zero = "0"

      instance Show Cell where
      show (Cell c x) = show (c,x)

      genPositions :: Int -> [(Int, Int)]
      genPositions x = [ (a,b) | a <- [0..(x-1)], b <- [0..(x-1)] ]

      genCellState :: Int -> CellState
      genCellState 0 = Zero
      genCellState 1 = One

      newBoard :: Int -> [Int] -> Board
      newBoard i [x] = [Cell (round $ sqrt(fromIntegral i), round $ sqrt(fromIntegral i)) (genCellState x)]
      where positions = genPositions $ round $ sqrt(fromIntegral i)
      newBoard i (x : xs) = [Cell (positions!!(i - 1 - length xs)) (genCellState x)] ++ newBoard i xs
      where positions = genPositions $ round $ sqrt(fromIntegral i)


      What improvements can I make to this, both in terms of good practises and performance? I don't like Board being a list of Cells. I posted this on Stack Overflow by accident (have since deleted it) and someone recommended changing type Board = [Cell] to newtype Board = Board getBoard :: Array (Int,Int) CellState but I'm not too familiar with arrays in Haskell so not sure how this would work exactly. From what I have read they apply a function to the elements in the range [Int..Int] and return a list of tuples with the input and output.







      array haskell






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 '17 at 1:00









      Jamal

      30.6k11121227




      30.6k11121227










      asked Nov 22 '17 at 0:54









      user6731064user6731064

      111




      111




















          1 Answer
          1






          active

          oldest

          votes


















          1












          $begingroup$

          By defining r = round . sqrt . fromIntegral, newBoard fits on the screen. positions doesn't appear to be used in newboard's first case.



          Half the code disappears if we interpret Cell as ((Int, Int), Int).



          newBoard's first case can be pushed one recursion call deeper, mapping [] to [] instead of [x] to the current right hand side.



          [_] ++ _ should be simplified as _ : _.



          positions is only used once, therefore I inline it.



          type Cell = ((Int, Int), Int) -- (position, state)

          genPositions :: Int -> [(Int, Int)]
          genPositions x = [ (a,b) | a <- [0..(x-1)], b <- [0..(x-1)] ]

          r = round . sqrt . fromIntegral

          newBoard :: Int -> [Int] -> [Cell]
          newBoard i [] = []
          newBoard i (x : xs) = (genPositions (r i)!!(i - 1 - length xs), x) : newBoard i xs


          Successive elements of the list returned by genPositions and xs are zipped together; zip captures this pattern. i is now not needed in its non-rooted form and I recommend changing the interface to take N as an argument instead. Non-square arguments can currently crash !! anyway. genPositions is only used once, therefore I inline it.



          type Cell = ((Int, Int), Int) -- (position, state)

          newBoard :: Int -> [Int] -> [Cell]
          newBoard n = zip $ liftA2 (,) [0..n-1] [0..n-1]


          For type Board = Array (Int, Int) Int, Data.Array allows newBoard n = listArray ((0,0),(n-1,n-1)).






          share|improve this answer











          $endgroup$













            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "196"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f181029%2fstoring-values-in-an-n-x-n-grid%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1












            $begingroup$

            By defining r = round . sqrt . fromIntegral, newBoard fits on the screen. positions doesn't appear to be used in newboard's first case.



            Half the code disappears if we interpret Cell as ((Int, Int), Int).



            newBoard's first case can be pushed one recursion call deeper, mapping [] to [] instead of [x] to the current right hand side.



            [_] ++ _ should be simplified as _ : _.



            positions is only used once, therefore I inline it.



            type Cell = ((Int, Int), Int) -- (position, state)

            genPositions :: Int -> [(Int, Int)]
            genPositions x = [ (a,b) | a <- [0..(x-1)], b <- [0..(x-1)] ]

            r = round . sqrt . fromIntegral

            newBoard :: Int -> [Int] -> [Cell]
            newBoard i [] = []
            newBoard i (x : xs) = (genPositions (r i)!!(i - 1 - length xs), x) : newBoard i xs


            Successive elements of the list returned by genPositions and xs are zipped together; zip captures this pattern. i is now not needed in its non-rooted form and I recommend changing the interface to take N as an argument instead. Non-square arguments can currently crash !! anyway. genPositions is only used once, therefore I inline it.



            type Cell = ((Int, Int), Int) -- (position, state)

            newBoard :: Int -> [Int] -> [Cell]
            newBoard n = zip $ liftA2 (,) [0..n-1] [0..n-1]


            For type Board = Array (Int, Int) Int, Data.Array allows newBoard n = listArray ((0,0),(n-1,n-1)).






            share|improve this answer











            $endgroup$

















              1












              $begingroup$

              By defining r = round . sqrt . fromIntegral, newBoard fits on the screen. positions doesn't appear to be used in newboard's first case.



              Half the code disappears if we interpret Cell as ((Int, Int), Int).



              newBoard's first case can be pushed one recursion call deeper, mapping [] to [] instead of [x] to the current right hand side.



              [_] ++ _ should be simplified as _ : _.



              positions is only used once, therefore I inline it.



              type Cell = ((Int, Int), Int) -- (position, state)

              genPositions :: Int -> [(Int, Int)]
              genPositions x = [ (a,b) | a <- [0..(x-1)], b <- [0..(x-1)] ]

              r = round . sqrt . fromIntegral

              newBoard :: Int -> [Int] -> [Cell]
              newBoard i [] = []
              newBoard i (x : xs) = (genPositions (r i)!!(i - 1 - length xs), x) : newBoard i xs


              Successive elements of the list returned by genPositions and xs are zipped together; zip captures this pattern. i is now not needed in its non-rooted form and I recommend changing the interface to take N as an argument instead. Non-square arguments can currently crash !! anyway. genPositions is only used once, therefore I inline it.



              type Cell = ((Int, Int), Int) -- (position, state)

              newBoard :: Int -> [Int] -> [Cell]
              newBoard n = zip $ liftA2 (,) [0..n-1] [0..n-1]


              For type Board = Array (Int, Int) Int, Data.Array allows newBoard n = listArray ((0,0),(n-1,n-1)).






              share|improve this answer











              $endgroup$















                1












                1








                1





                $begingroup$

                By defining r = round . sqrt . fromIntegral, newBoard fits on the screen. positions doesn't appear to be used in newboard's first case.



                Half the code disappears if we interpret Cell as ((Int, Int), Int).



                newBoard's first case can be pushed one recursion call deeper, mapping [] to [] instead of [x] to the current right hand side.



                [_] ++ _ should be simplified as _ : _.



                positions is only used once, therefore I inline it.



                type Cell = ((Int, Int), Int) -- (position, state)

                genPositions :: Int -> [(Int, Int)]
                genPositions x = [ (a,b) | a <- [0..(x-1)], b <- [0..(x-1)] ]

                r = round . sqrt . fromIntegral

                newBoard :: Int -> [Int] -> [Cell]
                newBoard i [] = []
                newBoard i (x : xs) = (genPositions (r i)!!(i - 1 - length xs), x) : newBoard i xs


                Successive elements of the list returned by genPositions and xs are zipped together; zip captures this pattern. i is now not needed in its non-rooted form and I recommend changing the interface to take N as an argument instead. Non-square arguments can currently crash !! anyway. genPositions is only used once, therefore I inline it.



                type Cell = ((Int, Int), Int) -- (position, state)

                newBoard :: Int -> [Int] -> [Cell]
                newBoard n = zip $ liftA2 (,) [0..n-1] [0..n-1]


                For type Board = Array (Int, Int) Int, Data.Array allows newBoard n = listArray ((0,0),(n-1,n-1)).






                share|improve this answer











                $endgroup$



                By defining r = round . sqrt . fromIntegral, newBoard fits on the screen. positions doesn't appear to be used in newboard's first case.



                Half the code disappears if we interpret Cell as ((Int, Int), Int).



                newBoard's first case can be pushed one recursion call deeper, mapping [] to [] instead of [x] to the current right hand side.



                [_] ++ _ should be simplified as _ : _.



                positions is only used once, therefore I inline it.



                type Cell = ((Int, Int), Int) -- (position, state)

                genPositions :: Int -> [(Int, Int)]
                genPositions x = [ (a,b) | a <- [0..(x-1)], b <- [0..(x-1)] ]

                r = round . sqrt . fromIntegral

                newBoard :: Int -> [Int] -> [Cell]
                newBoard i [] = []
                newBoard i (x : xs) = (genPositions (r i)!!(i - 1 - length xs), x) : newBoard i xs


                Successive elements of the list returned by genPositions and xs are zipped together; zip captures this pattern. i is now not needed in its non-rooted form and I recommend changing the interface to take N as an argument instead. Non-square arguments can currently crash !! anyway. genPositions is only used once, therefore I inline it.



                type Cell = ((Int, Int), Int) -- (position, state)

                newBoard :: Int -> [Int] -> [Cell]
                newBoard n = zip $ liftA2 (,) [0..n-1] [0..n-1]


                For type Board = Array (Int, Int) Int, Data.Array allows newBoard n = listArray ((0,0),(n-1,n-1)).







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited 9 mins ago









                200_success

                131k17157422




                131k17157422










                answered Nov 22 '17 at 23:49









                GurkenglasGurkenglas

                2,949512




                2,949512



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f181029%2fstoring-values-in-an-n-x-n-grid%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

                    Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

                    Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar