Compare commits

...

2 Commits

Author SHA1 Message Date
Bram van den Heuvel fcc7699a44 elm-format Hashdict & Iddict
I should attempt to not forget this!
2023-12-14 20:43:23 +01:00
Bram van den Heuvel 41ede5bbff Add Hashdict 2023-12-14 18:35:27 +01:00
3 changed files with 322 additions and 21 deletions

View File

@ -6,6 +6,7 @@
"version": "1.0.0",
"exposed-modules": [
"Matrix",
"Internal.Tools.Hashdict",
"Internal.Tools.Iddict"
],
"elm-version": "0.19.0 <= v < 0.20.0",

View File

@ -0,0 +1,267 @@
module Internal.Tools.Hashdict exposing
( Hashdict
, empty, singleton, insert, remove, removeKey
, isEmpty, member, memberKey, get, size
, keys, values, toList, fromList
, rehash, union
, encode, decoder, softDecoder
)
{-| This module abstracts the `Dict` type with one function that assigns a
unique identifier for each value based on a function that assigns each value.
This allows you to store values based on an externally defined identifier.
## Dictionaries
@docs Hashdict
## Build
@docs empty, singleton, insert, remove, removeKey
## Query
@docs isEmpty, member, memberKey, get, size
## Lists
@docs keys, values, toList, fromList
## Transform
@docs rehash, union
## JSON coders
@docs encode, decoder, softDecoder
-}
import FastDict as Dict exposing (Dict)
import Json.Decode as D
import Json.Encode as E
{-| A dictionary of keys and values where each key is defined by its value. For
example, this can be useful when every user is identifiable by their username:
import Hashdict exposing (Hashdict)
users : Hashdict User
users =
Hashdict.fromList .name
[ User "Alice" 28 1.65
, User "Bob" 19 1.82
, User "Chuck" 33 1.75
]
type alias User =
{ name : String
, age : Int
, height : Float
}
In the example listed above, the users are stored by their username, which means
that all you need to know is the value "Alice" to retrieve all the information
about them. Additionally, you do not need to specify a key to insert the values.
-}
type Hashdict a
= Hashdict
{ hash : a -> String
, values : Dict String a
}
{-| Decode a hashdict from a JSON value. To create a hashdict, you are expected
to insert a hash function. If the hash function doesn't properly hash the values
as expected, the decoder will fail to decode the hashdict.
-}
decoder : (a -> String) -> D.Decoder a -> D.Decoder (Hashdict a)
decoder f xDecoder =
D.keyValuePairs xDecoder
|> D.andThen
(\items ->
if List.all (\( hash, value ) -> f value == hash) items then
items
|> Dict.fromList
|> (\d -> { hash = f, values = d })
|> Hashdict
|> D.succeed
else
D.fail "Hash function fails to properly hash all values"
)
{-| Create an empty hashdict.
-}
empty : (a -> String) -> Hashdict a
empty hash =
Hashdict { hash = hash, values = Dict.empty }
{-| Encode a Hashdict into a JSON value. Keep in mind that an Elm function
cannot be universally converted to JSON, so it is up to you to preserve that
hash function!
-}
encode : (a -> E.Value) -> Hashdict a -> E.Value
encode encodeX (Hashdict h) =
h.values
|> Dict.toList
|> List.map (Tuple.mapSecond encodeX)
|> E.object
{-| Convert an association list into a hashdict.
-}
fromList : (a -> String) -> List a -> Hashdict a
fromList hash xs =
Hashdict
{ hash = hash
, values =
xs
|> List.map (\x -> ( hash x, x ))
|> Dict.fromList
}
{-| Get the value associated with a hash. If the hash is not found, return
`Nothing`. This is useful when you are not sure if a hash will be in the
hashdict.
-}
get : String -> Hashdict a -> Maybe a
get k (Hashdict h) =
Dict.get k h.values
{-| Insert a value into a hashdict. The key is automatically generated by the
hash function. If the function generates a collision, it replaces the existing
value in the hashdict.
-}
insert : a -> Hashdict a -> Hashdict a
insert v (Hashdict h) =
Hashdict { h | values = Dict.insert (h.hash v) v h.values }
{-| Determine if a hashdict is empty.
-}
isEmpty : Hashdict a -> Bool
isEmpty (Hashdict h) =
Dict.isEmpty h.values
{-| Get all of the hashes in a hashdict, sorted from lowest to highest.
-}
keys : Hashdict a -> List String
keys (Hashdict h) =
Dict.keys h.values
{-| Determine if a value's hash is in a hashdict.
-}
member : a -> Hashdict a -> Bool
member value (Hashdict h) =
Dict.member (h.hash value) h.values
{-| Determine if a hash is in a hashdict.
-}
memberKey : String -> Hashdict a -> Bool
memberKey key (Hashdict h) =
Dict.member key h.values
{-| Remap a hashdict using a new hashing algorithm.
-}
rehash : (a -> String) -> Hashdict a -> Hashdict a
rehash f (Hashdict h) =
Hashdict
{ hash = f
, values =
h.values
|> Dict.values
|> List.map (\v -> ( f v, v ))
|> Dict.fromList
}
{-| Remove a value from a hashdict. If the value's hash is found, the key-value
pair is removed. If the value's hash is not found, no changes are made.
hdict |> Hashdict.remove (User "Alice" 19 1.82)
-}
remove : a -> Hashdict a -> Hashdict a
remove v (Hashdict h) =
Hashdict { h | values = Dict.remove (h.hash v) h.values }
{-| Remove a key from a hashdict. If the key is not found, no changes are made.
hdict |> Hashdict.removeKey "Alice"
-}
removeKey : String -> Hashdict a -> Hashdict a
removeKey k (Hashdict h) =
Hashdict { h | values = Dict.remove k h.values }
{-| Create a hashdict with a single key-value pair.
-}
singleton : (a -> String) -> a -> Hashdict a
singleton f v =
empty f |> insert v
{-| Determine the number of values in a hashdict.
-}
size : Hashdict a -> Int
size (Hashdict h) =
Dict.size h.values
{-| Decode a hashdict from a JSON value. If you cannot deduce the originally
used hash function, (or if you simply do not care) you can use this function to
decode and rehash the Hashdict using your new hash function.
-}
softDecoder : (a -> String) -> D.Decoder a -> D.Decoder (Hashdict a)
softDecoder f xDecoder =
D.keyValuePairs xDecoder
|> D.map (List.map Tuple.second >> fromList f)
{-| Convert a hashdict into an association list of key-value pairs, sorted by
keys.
-}
toList : Hashdict a -> List ( String, a )
toList (Hashdict h) =
Dict.toList h.values
{-| Combine two hashdicts under the hash function of the first. If there is a
collision, preference is given to the first hashdict.
-}
union : Hashdict a -> Hashdict a -> Hashdict a
union (Hashdict h1) hd2 =
case rehash h1.hash hd2 of
Hashdict h2 ->
Hashdict
{ hash = h1.hash
, values = Dict.union h1.values h2.values
}
{-| Get all values stored in the hashdict, in the order of their keys.
-}
values : Hashdict a -> List a
values (Hashdict h) =
Dict.values h.values

View File

@ -1,4 +1,11 @@
module Internal.Tools.Iddict exposing (Iddict, decoder, empty, encode, get, insert, isEmpty, keys, map, member, remove, singleton, size, values)
module Internal.Tools.Iddict exposing
( Iddict
, empty, singleton, insert, map, remove
, isEmpty, member, get, size
, keys, values
, encode, decoder
)
{-| The id-dict is a data type that lets us store values in a dictionary using
unique identifiers. This can be used as a dictionary where the keys do not
matter.
@ -6,39 +13,47 @@ matter.
The benefit of the iddict is that it generates the keys FOR you. This way, you
do not need to generate identifiers yourself.
## Id-dict
@docs Iddict
## Build
@docs empty, singleton, insert, map, remove
## Query
@docs isEmpty, member, get, size
## Lists
@docs keys, values
## JSON coders
@docs encode, decoder
-}
import FastDict as Dict exposing (Dict)
import Json.Decode as D
import Json.Encode as E
{-| The Iddict data type.
-}
type Iddict a
= Iddict
= Iddict
{ cursor : Int
, dict : Dict Int a
}
{-| Decode an id-dict from a JSON value.
-}
decoder : D.Decoder a -> D.Decoder (Iddict a)
@ -50,27 +65,32 @@ decoder xDecoder =
dict =
pairs
|> List.filterMap
(\(k, v) ->
(\( k, v ) ->
k
|> String.toInt
|> Maybe.map (\n -> (n, v))
|> String.toInt
|> Maybe.map (\n -> ( n, v ))
)
|> Dict.fromList
in
Iddict
{ cursor =
Dict.keys dict -- Larger than all values in the list
|> List.map ((+) 1)
|> List.maximum
|> Maybe.withDefault 0
|> max (Dict.size dict) -- At least the dict size
|> max c -- At least the given value
, dict = dict
}
Iddict
{ cursor =
Dict.keys dict
-- Larger than all values in the list
|> List.map ((+) 1)
|> List.maximum
|> Maybe.withDefault 0
|> max (Dict.size dict)
-- At least the dict size
|> max c
-- At least the given value
, dict = dict
}
)
(D.field "cursor" D.int)
(D.field "dict" <| D.keyValuePairs xDecoder)
{-| Create an empty id-dict.
-}
empty : Iddict a
@ -80,25 +100,28 @@ empty =
, dict = Dict.empty
}
{-| Encode an id-dict to a JSON value.
-}
encode : (a -> E.Value) -> Iddict a -> E.Value
encode encodeX (Iddict d) =
E.object
[ ( "cursor", E.int d.cursor )
, ( "dict",
d.dict
, ( "dict"
, d.dict
|> Dict.toCoreDict
|> E.dict String.fromInt encodeX
)
]
{-| Get a value from the id-dict using its key.
-}
get : Int -> Iddict a -> Maybe a
get k (Iddict { dict }) =
Dict.get k dict
{-| Insert a new value into the id-dict. Given that the id-dict generates its
key, the function returns both the updated id-dict as the newly generated key.
@ -107,25 +130,29 @@ key, the function returns both the updated id-dict as the newly generated key.
case x of
( _, iddict ) ->
get 0 iddict -- Just "hello"
-}
insert : a -> Iddict a -> (Int, Iddict a)
insert : a -> Iddict a -> ( Int, Iddict a )
insert v (Iddict d) =
( d.cursor
, Iddict { cursor = d.cursor + 1, dict = Dict.insert d.cursor v d.dict }
)
{-| Determine if an id-dict is empty.
-}
isEmpty : Iddict a -> Bool
isEmpty (Iddict d) =
Dict.isEmpty d.dict
{-| Get all of the keys from the id-dict, sorted from lowest to highest.
-}
keys : Iddict a -> List Int
keys (Iddict { dict }) =
Dict.keys dict
{-| Map an existing value at a given key, if it exists. If it does not exist,
the operation does nothing.
-}
@ -133,23 +160,28 @@ map : Int -> (a -> a) -> Iddict a -> Iddict a
map k f (Iddict d) =
Iddict { d | dict = Dict.update k (Maybe.map f) d.dict }
{-| Determine if a key is in an id-dict.
-}
member : Int -> Iddict a -> Bool
member k (Iddict d) =
k < d.cursor && Dict.member k d.dict
{-| Remove a key-value pair from the id-dict. If the key is not found, no
{-| Remove a key-value pair from the id-dict. If the key is not found, no
changes are made.
-}
remove : Int -> Iddict a -> Iddict a
remove k (Iddict d) =
Iddict { d | dict = Dict.remove k d.dict }
{-| Create an id-dict with a single value.
-}
singleton : a -> (Int, Iddict a)
singleton v = insert v empty
singleton : a -> ( Int, Iddict a )
singleton v =
insert v empty
{-| Determine the number of key-value pairs in the id-dict.
-}
@ -157,6 +189,7 @@ size : Iddict a -> Int
size (Iddict d) =
Dict.size d.dict
{-| Get all of the values from an id-dict, in the order of their keys.
-}
values : Iddict a -> List a