[Haskell] How to implement Association-Lists and Property-Lists
in Haskell
Philip Weaver
philip.weaver at gmail.com
Wed May 26 06:15:09 EDT 2010
Hello! You have several options. First, consider that when you lookup (see
Prelude.find) a field in the alist, you're going to stop as soon as you find
the first match. So, as long as you're appending new fields to the front of
list, then you'll be ok (it will be correct, but not efficient).
If I understand correctly, you want to be able to associate up to one value
with Root, one with Oct, and one with Mode. In that case, you may want to
define your alist like this:
data Key = Root | Oct | Mode deriving (Show, Eq)
type AList a = [(Key, a)]
Then, you can do Prelude.lookup Root, Prelude.lookup Oct, and Prelude.lookup
Mode to get the respective values from the AList.
Finally, you may want to use Data.Map. It provides an efficient AList.
Hope that helps!
- Philip
On Wed, May 26, 2010 at 2:59 AM, Tom Jordan <viresh53 at gmail.com> wrote:
> Greetings,
>
> I'm struggling to find a way to define an "Alist" once, and then simply
> add-in "Fields" to it incrementally.. without having to keep using new
> identifiers/variables to hold the result of each "addin" expression.
> I understand that pure Functional Programming doesn't use destructive state
> changes, but I'm wondering if there is a way to make this happen using
> Monads, for example (which I have a cursory understanding of..)
>
> Instead of doing this:
>
> type Root = String
> type Oct = Integer
> type Mode = Integer
>
> data Field = Root Root | Oct Oct | Mode Mode deriving (Show)
>
> type Alist = [Field]
>
> addin :: Alist -> Field -> Alist
> addin p f = f:p
>
> p0 :: Alist
> p0 = []
> p1 = addin p0 (Root "c")
> p2 = addin p1 (Oct 4)
> p3 = addin p2 (Mode 3)
> p4 = addin p3 (Oct 3)
> -- ... p42, etc
>
>
> For the Alist version, when adding-in a Field with the same
> constructor-name as one that has already been added-in, it adds-in a brand
> new entry (with a repeated key-name (in the form of another constructor) and
> its associated value), as a normal association list does..
>
> I'm also looking to define a Property-List version, where a
> Field-name/constructor can update a previous value (if the Field has already
> been added), or add-in a new entry if the Field hasn't been added yet.
>
>
> Many Thanks,
>
> Tom Jordan
>
> _______________________________________________
> Haskell mailing list
> Haskell at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell/attachments/20100526/478ff15f/attachment-0001.html
More information about the Haskell
mailing list