开发者

How to show all the tuple data in a list (using recursion)

Imagine I have a tuple list like

 [("Fazaal","Naufer",07712345678)
            ,("Tharanga","Chandasekara",0779876543)
            ,("Ruaim","Mo开发者_JAVA技巧homad",07798454545)
            ,("Yasitha","Lokunarangoda",07798121212)
            ,("Rochana","Wimalasena",0779878787)
            ,("Navin","Dhananshan",077987345678)
            ,("Akila","Silva",07798123123)
            ,("Sudantha","Gunawardana",0779812456)
            ] 

I want to show each tuple here. I tried this code but it messes the format up.

displayDB           :: [Reservation] ->String 
displayDB []        =   []
displayDB (x :xs)   =   show x ++ show( displayDB (xs))


First, you are calling "show" on the string output of "displayDB". Your last line should be

displayDB (x :xs)   =   show x ++ displayDB xs

Your version will cause each successive tuple to be enclosed in another layer of string escaping, so you will get progressively more complex escaping.

Second, "show x" will convert the tuple into a string in the most obvious and basic way. You probably want a better function than that which emits the fields in a nicer way, and you will also want to interpolate commas or newlines as appropriate. Without knowing what you want this output for its a bit difficult to tell.

Third, it's bad style to write a recursive function of your own (unless you are writing this as an exercise); a better style is to compose functions like "map". The expression

map show xs

will turn your list of tuples into a list of strings. You can then print these strings or use "intercalate" in Data.List to turn this list of strings into a single string with the right bits put in between the elements. So you probably want something like

displayDB xs = intercalate ",\n" $ map show xs

Or if you prefer it in point-free form:

displayDB = intercalate ",\n" . map show


Consider what happens on smaller input. Each line is an expansion:

displayDB [("A", "B", 1), ("C", "D", 2)]
=> show ("A", "B", 1) ++ show (displayDB [("C", "D", 2)])
=> show ("A", "B", 1) ++ show (show ("C", "D", 2) ++ show (displayDB []))
=> show ("A", "B", 1) ++ show (show ("C", "D", 2) ++ show [])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜