Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

How to convert my own Data constructor to List in Haskell

I have just started trying Haskell after using Python, and I'm facing a lot of problems understanding it

for example after I tried to make a new type called ListBag and writing a simple function to convert list to ListBag I can't go back and do anything with that data:

data ListBag a = LB [(a,Int)] deriving (Show,Eq)

fromList :: (Ord a) => [a] ->ListBag a
fromList xs = LB [ y| y<- ys]
            where ys = toList(fromListWith (+) [(x, 1) | x <- xs])

a :: [Integer]
a=[1,1,1,1,1,1,2,2,2,3,3,3,3,4,5,5]
b = fromList a

Now b is:

LB [(1,6),(2,3),(3,4),(4,1),(5,2)]

and because b is b :: ListBag Integer it can't be mapped or ... So how can I convert it to List again?

question from:https://stackoverflow.com/questions/65853042/how-to-convert-my-own-data-constructor-to-list-in-haskell

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Firstly, your ListBag doesn't save order in which elements was in initial list, but... you can convert ListBag a to [a] like so:

toList :: ListBag a -> [a]
toList (LB ys) = concat $ ((y, n) -> replicate n y) <$> ys

And you can redefine your fromList as

fromList xs = LB $ toList $ fromListWith (+) [ (x, 1) | x <- xs]

Because [ y | y <- ys] ~ ys and x where x = y ~ y


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...