haskell - Recursively calling in a show function

I am taking in a data type MyList which has a tail with list and a head. Need to turn it into a reversed string like the haskell data type list.

showList :: MyList a -> String
showlist (MyList h t) =  show(showlist(t) ++ show( h : [] ))

I am getting out this craziness for showList [1,2,3]


1 Answer

  1. Abel- Reply


    You are basically calling show two times: you don't need that, once you got a string that's all what is required to implement show. So instead of this:

    Prelude> show [1,2,3]

    you are getting:

    Prelude> show $ show [1,2,3]

    And that's because in order to print " Haskell needs to escape those with \.

    Let's go back to your definition, you are trying to define a function of type MyList a -> String, so basically we'll need to call show only over the elements of type a (I'd assume h is of type a, and this type is an instance of Show):

    showList :: (Show a) => MyList a -> String
    showList Nil = ""
    showlist (MyList h t) =  showlist(t) ++ show(h : [])

    I'm assuming your list type is something like:

    data MyList a = Nil | MyList a (MyList a)

    So you'll get (I don't know why you are reversing the list when showing):

    Prelude> showList (MyList 1 (MyList 2 Nil))

    If you want, you can improve a little bit your show function by using ,:

    showList :: (Show a) => MyList a -> String
    showList Nil = ""
    showlist (MyList h t) =  show h ++ "," ++ showlist t

    Hence, you'll get:

    Prelude> showList (MyList 1 (MyList 2 Nil))

    I leave you as an exercise how to properly place ,,[ and ] to print likewise:


Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>