Luxzero
Luxzero

Reputation: 43

Displaying a list with another aspect

I would like to know if it's possible for a list like this:

FavoriteList [('d',False), ('e',True), ('c',False)]

To be simply displayed like this:

{'d', 'e'*, 'c'}

Upvotes: 1

Views: 114

Answers (1)

Random Dev
Random Dev

Reputation: 52270

assuming you are talking about

favoriteList :: [(Char, Bool)]
favoriteList = [('d',False), ('e',True), ('c',False)]

and you want a list ['d','e','c'] (I hope the * got there by accident) then it's just

λ> map fst favoriteList
"dec"

(where a list of characters is displayed as as string).


assuming you want the {...} format then you have to work a bit more. Using Data.List.intersperse to weave in the ", "s and an additional show to get the ' ' you can do it with:

λ> import Data.List(intersperse)
λ> "{" ++ (concat . intersperse ", " $ map (show . fst) favoriteList) ++ "}"
"{'d', 'e', 'c'}"

in case you are interested in the steps:

λ> map fst favoriteList
"dec"
λ> map (show . fst) favoriteList
["'d'","'e'","'c'"]
λ> intersperse ", " $ map (show . fst) favoriteList
["'d'",", ","'e'",", ","'c'"]
λ> concat . intersperse ", " $ map (show . fst) favoriteList
"'d', 'e', 'c'"

the "{" ++ (..) ++ "}" should be obvious I hope


assuming the * is in there because the second part of the tuple was true then you can do it like this:

λ> let stared (c,star) = if star then show c ++ "*" else show c
λ> "{" ++ (concat . intersperse ", " $ map stared favoriteList) ++ "}"
"{'d', 'e'*, 'c'}"

further assuming the FavoriteList was not a typo but a data-constructor:

data FavoriteList = FavoriteList [(Char, Bool)]

myList :: FavoriteList
myList = FavoriteList [('d',False), ('e',True), ('c',False)]

it's

λ> let stared (c,star) = if star then show c ++ "*" else show c
λ> let (FavoriteList xs) = myList in "{" ++ (concat . intersperse ", " $ map (stared) xs) ++ "}"
"{'d', 'e'*, 'c'}"

where I just used pattern-matching to get out the list again


complete code

import Data.List(intercalate)

data FavoriteList = FavoriteList [(Char, Bool)]

myList :: FavoriteList
myList = FavoriteList [('d',False), ('e',True), ('c',False)]

printList :: FavoriteList -> String
printList (FavoriteList xs) = 
  "{" ++ (intercalate ", " $ map stared xs) ++ "}"
  where  stared (c,star) = if star then show c ++ "*" else show c

(PS: as Chi pointed out I should have used intercalate = concat . intersperse instead) example

λ> printList myList
"{'d', 'e'*, 'c'}"

*I hope that was all ;) *

Upvotes: 4

Related Questions