Home > Blockchain >  How to make a show instance for a List with foldr?
How to make a show instance for a List with foldr?

Time:12-07

I want to write my own show instance for my Datatype "My list". So far my approach works, but I always have a comma at the end. I already tried to start the Fold with the last element and remove it from the list, but it is quit cumbersome and it didn't work. Is there an easier way to get the right solution?

actual {1, 2, 3,} -> expected {1, 2, 3}

instance Show a => Show (Mylist1 a) where
  show (Mylist1 []) = "{}"
  show (Mylist1 xs) = "{"    foldr (\x y -> show x    ","    y) "}" xs 

CodePudding user response:

Since you already split out the case of an empty list, why not make use of the first element of the non-empty one?

instance Show a => Show (Mylist1 a) where
  show (Mylist1 []) = "{}"
  show (Mylist1 (x:xs)) = "{"    show x    foldr (\x y -> ","    show x    y) "}" xs 

CodePudding user response:

There is intercalate

import Data.List
instance Show a => Show (Mylist1 a) where
  show (Mylist1 xs) = '{' : intercalate ", " (map show xs)    "}"

CodePudding user response:

If you really want to use pure foldr without any pattern matching on show parameters, then you can to this trick with accumulating continuation and applying parameters to it, so the computation built is aware of the element index it's currently processing.

show (Mylist l) =
  foldr
    (\el cont n acc -> ((if n == 0 then "{" else ",")    show el)    cont (n   1) acc)
    (\n x -> if n == 0 then "{}" else x)
    l
    0 "}"

But it's an overkill, don't use it unless you for some reason have to express the whole thing in a single foldr.

  • Related