Deece5531
Deece5531

Reputation: 45

How do I initialize a type alias like this in Elm?

 type alias Bag a = List (a, Int)

I am trying to create functions that work with this type alias but I can't figure out how to return a Bag from a function.. Like in the following function I am hoping to insert a new item into an existing bag (could be empty, which is the only case I am trying to get working at the moment).

insert : a -> Bag a -> Bag a
insert b c = case c of
   [] -> Bag a : [(b, 1)]

 --this case below is what I'm hoping could work out..cant really check without getting the first case to work---
 x::xs -> if Tuple.first x == b 
         then Bag a : [(b, (Tuple.second x) + 1)] ++ xs
         else [x] ++ insert b xs

How can I initialize a new Bag without using this multi-line method below?

testBag : Bag Int
testBag = [(5,1),(2,1)]

PS very new to Elm and struggling to find resources that can help me shift from an imperative mindset..

Upvotes: 2

Views: 193

Answers (1)

AndrewC
AndrewC

Reputation: 32455

You don't need to write Bag a: in front of bags. The compiler can deduce what type you need.

You do need to match up the indentation for the different branches of your case:

insert : a -> Bag a -> Bag a
insert b c = case c of
   [] ->  [(b, 1)]
   x::xs -> if Tuple.first x == b
     then  [(b, (Tuple.second x) + 1)] ++ xs
     else [x] ++ insert b xs

This works, but I wouldn't have written it that way. I'd have used pattern matching to split b into the item and count rather than Tuple.first and Tuple.second, and I'd use more descriptive names for the variables, giving:

add : a -> Bag a -> Bag a
add item bag =
    case bag of
        [] -> [ ( item, 1 ) ]
        ( firstItem, count ) :: otherItems ->
                if item == firstItem then
                    ( firstItem, count + 1 ) :: otherItems
                else
                    ( firstItem, count ) :: add item otherItems

I'd also define

emptyBag : Bag a
emptyBag = []

so that you can make

exampleBag : Bag Int
exampleBag = emptyBag |> add 5 |> add 3 |> add 5 |> add 3 |> add 3

By the way, most IDEs can run elm-format automatically for you when you save your work. That would lay out your code to be better maintainable and more easily readable. Other elm programmers would find it easier to read your code because it would be in the frequently-used elm layout.

Upvotes: 5

Related Questions