Home > Back-end >  Haskell : list comprehension
Haskell : list comprehension

Time:12-02

How can I write this code without repeating (c !! x) where is x = [0..7], using list comprehension is better but I couldn't figure how to write it

show (EOBoard f c r) = "EOBoard\n"    "Foundations "
      show f    "\n"    "Columns \n" 
      show (c!!0)    "\n"    show (c!!1)    "\n"
      show (c!!2)    "\n"    show (c!!3)    "\n"
      show (c!!4)    "\n"    show (c!!5)    "\n"
      show (c!!6)    "\n"    show (c!!7)    "\n"
      "Reserves "    show r

CodePudding user response:

Let's start by getting rid of all those manual line breaks.

show (EOBoard f c r) = unlines $
  [ "EOBoard"
  , "Foundations "    show f
  , "Columns" 
  , show (c!!0)
  , show (c!!1)
  , show (c!!2)
  , show (c!!3)
  , show (c!!4)
  , show (c!!5)
  , show (c!!6)
  , show (c!!7)
  , "Reserves "    show r]

As you noticed, there's a rather repetitive section. Also, those !! applications are kind of expensive. A list comprehension solves both problems, but I'd use map instead.

show (EOBoard f c r) = unlines $
  [ "EOBoard"
  , "Foundations "    show f
  , "Columns" ]   
  map show c
  ["Reserves "    show r]

There's still something funny; Show really isn't for pretty-printing. show really shouldn't insert line breaks. You probably actually want to write a custom pretty-printing function instead.

CodePudding user response:

What you wrote is equivalent to

show (EOBoard f c r) = "EOBoard\n"    "Foundations "
      show f    "\n"    "Columns \n"   
      concat [ show s    "\n" | s <- take 8 c]
      "\n"    "Reserves "    show r

which is equivalent to

show (EOBoard f c r) = "EOBoard\n"    "Foundations "
      show f    "\n"    "Columns \n"   
      [ ch | s <- take 8 c, ch <- show s    "\n" ]
      "\n"    "Reserves "    show r

or, using the concat more instead of inlining it, it is equivalent to

show (EOBoard f c r) = concat (
   [ "EOBoard\n", "Foundations ", show f, "\n", "Columns \n" ]
      [ show s    "\n" | s <- take 8 c]
      ["\n" , "Reserves " , show r] )

which is normally written with the $ operator, as

show (EOBoard f c r) = concat $
   [ "EOBoard\n", "Foundations ", show f, "\n", "Columns \n" ]
      [ show s    "\n" | s <- take 8 c]
      ["\n" , "Reserves " , show r]
  • Related