Sir Hadez
Sir Hadez

Reputation: 23

Haskell change the order of a list

so I have this module that creates a list of favorites, when i add something to the list i want it to appear in the end of the list. For example

let l1 = foldr add empty "bacaaced"

The result should be {'d', 'e', 'c', 'a', 'b'}

Note : The result appear that way cause i have a Show instance implemented.

And my result is { 'b' , 'a' , 'c', 'e', 'd'}

I have tried to reverse the input string but didnt managed to make it work, can anyone help me with this?

module MyModule
( ListFav(..)
, empty
, add
) where

data ListFav a = Elem (a,Bool) (ListFav a ) | Empty deriving (Show)

empty :: ListFav a
empty = Empty

inList :: Eq a => a -> ListFav a -> Bool
inList y (Elem (x,_) (xs))
   | y == x = True
   | xs == Empty = False
   | otherwise = inList y xs

add :: Eq a => a -> ListFav a -> ListFav a
add x Empty = Elem(x,False) Empty
add x xs 
   | inList x xs == True = xs   
   | otherwise = Elem (x,False) xs

Upvotes: 2

Views: 521

Answers (3)

MathematicalOrchid
MathematicalOrchid

Reputation: 62818

So, add checks whether x is in the list, and if it isn't, it adds it to the start of the list. Presumably you meant to add it to the end of the list?

Why not do it like this:

add :: Eq a => a -> ListFav a -> ListFav a
add x Empty = Elem (x, False) Empty
add x ys@(Elem (y,t) ys2) = if x == y then ys else Elem (y,t) (add x ys2)

That is, see if the first element is the one you're asked to add. If it is, we're done. If it isn't, recursively look at the next item. If you get to the end without finding the item, then add it.

Upvotes: 1

erisco
erisco

Reputation: 14319

Maybe I am missing the point, but you can solve this simply with base functions. Try reverse . nub or nub . reverse.

Upvotes: 0

9000
9000

Reputation: 40884

You explicitly put the last added result at the top of your list in the very last line: Elem (x, False) xs.

If you just want to print the result in "chronological" order, you can implement Show on your own and reverse the list there.

Also, you could potentially add your element at the end rather economically, since you scan the entire list for duplicates anyway. You could do the scanning and rebuilding in the same go.

Upvotes: 0

Related Questions