我想知道这样的列表是否可能:
FavoriteList [('d',False), ('e',True), ('c',False)]
简单地显示如下:
{'d', 'e'*, 'c'}
答案 0 :(得分:4)
假设您正在谈论
favoriteList :: [(Char, Bool)]
favoriteList = [('d',False), ('e',True), ('c',False)]
你需要一个列表['d','e','c']
(我希望*
偶然到达那里)
那就是
λ> map fst favoriteList
"dec"
(其中字符列表显示为字符串)。
假设您需要{...}
格式,那么您必须多做一些工作。
在Data.List.intersperse
中使用", "
编织,在show
添加' '
以获得λ> import Data.List(intersperse)
λ> "{" ++ (concat . intersperse ", " $ map (show . fst) favoriteList) ++ "}"
"{'d', 'e', 'c'}"
,您可以使用以下内容进行操作:
λ> 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'"
如果您对以下步骤感兴趣:
"{" ++ (..) ++ "}"
*
应该是显而易见的,我希望
假设true
在那里,因为元组的第二部分是λ> let stared (c,star) = if star then show c ++ "*" else show c
λ> "{" ++ (concat . intersperse ", " $ map stared favoriteList) ++ "}"
"{'d', 'e'*, 'c'}"
,那么你可以这样做:
FavoriteList
进一步假设data FavoriteList = FavoriteList [(Char, Bool)]
myList :: FavoriteList
myList = FavoriteList [('d',False), ('e',True), ('c',False)]
不是拼写错误而是数据构造函数:
λ> 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'}"
它的
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
我刚刚使用模式匹配来再次列出该列表
intercalate = concat . intersperse
( PS :Chi指出我应该使用λ> printList myList
"{'d', 'e'*, 'c'}"
代替)
示例
jspm install github:mygithubaccount/myplugin@master
*我希望这就是全部;)*