codesnippets:recordsyntax

This is an old revision of the document!


Record syntax

Advantages

  • can document the intended use of fields
    • see example 1
  • provides functions to get the records content
    • see example 2
  • example 1:
    • {-| to be able to print into a 'CharMatrix'
       
      * prefix: xc
      * instance of Formatting to print the stored characters
      -}
      data MatrixCursor = 
          MatrixCursor {
              -- | the row, starting at 0
              rnRow :: Integer, 
              -- | the column starting at 0
              rnCol :: Integer }
          deriving Show
  • example 2:

Disadvantages

With sum types combined: risk of runtime errors

An algebraic sum type (see also https://en.wikipedia.org/wiki/Algebraic_data_type regarding sum types) is a type with different constructors seperated by |. Record syntax can generate errors, if combined with sum types.

  • example:
    • module Main where
       
      main :: IO ()
      main = do
          print $ nDiameterInMM SomethingElse
       
      data Wood = Log { nDiameterInMM :: Float,  nLengthInMM :: Float } | SomethingElse
          deriving Show
  • output:
    • Test2-exe.exe: No match in record selector nDiameterInMM

Risk of namespace colisions without strong coding rules

module Main where
 
main :: IO ()
main = do
    print $ nCol xc
 
{-| to be able to print into a 'CharMatrix'
 
* prefix: xc
* instance of Formatting to print the stored characters
-}
data MatrixCursor = 
    MatrixCursor {
        -- | the row, starting at 0
        nRow :: Integer, 
        -- | the column starting at 0
        nCol :: Integer }
    deriving Show
 
xc :: MatrixCursor
xc = incMatrixCursorCol 5 $ incMatrixCursorCol 2 $ incMatrixCursorCol 3 $ initMatrixCursor
 
incMatrixCursorCol :: Integer -> MatrixCursor -> MatrixCursor
incMatrixCursorCol n (MatrixCursor nRow nCol) = (MatrixCursor nRow (nCol+n))
 
initMatrixCursor :: MatrixCursor
initMatrixCursor = (MatrixCursor 0 0)
  • compiler warning:
    • app\Main.hs:25:36: warning: [-Wname-shadowing]
          This binding for `nRow' shadows the existing binding
            defined at app\Main.hs:16:9
         |
      25 | incMatrixCursorCol n (MatrixCursor nRow nCol) = (MatrixCursor nRow (nCol+n))
         |                                    ^^^^
This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
You could leave a comment if you were logged in.
codesnippets/recordsyntax.1616266664.txt.gz · Last modified: (external edit)

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki