I have confusion using types which are functions.
Let say I want to implement a dictionary, which when given a and b returns Maybe b.
type Dict a b = a->Maybe b
How can I implement an insertion function for this dictionary?
insertDict :: (Eq a) => a -> b -> (Dict a b)-> (Dict a b)
I have come up with the following thing
insertDict x y mydict = \a->Just y
but it is not correct and will discard the previous dictionary.
Everything in Haskell has a type, so the compiler can reason quite a lot about your program before compiling it. Unlike Java or Pascal, Haskell has type inference.
The most basic way of defining a function in Haskell is to ``declare'' what it does. For example, we can write: double :: Int -> Int double n = 2*n. Here, the first line specifies the type of the function and the second line tells us how the output of double depends on its input.
Allow the use and definition of types with operator names. The language TypeOperators allows you to use infix operators in types. Operator symbols are constructors rather than type variables (as they are in terms).
You can use a "chain of responsibility" pattern: the insert function checks if the argument to the result Dict
matches with its own key, otherwise it delegates on the previous Dict
which received as argument.
type Dict a b = a -> Maybe b
insertDict :: (Eq a) => a -> b -> Dict a b -> Dict a b
-- Note that the k' is the argument of the result dict function
insertDict k v dict k' = if k == k' then Just v else dict k'
emptyDict :: Dict a b
emptyDict _ = Nothing
Some examples in ghci:
Λ insertDict 'a' (1::Int) emptyDict $ 'a'
Just 1
Λ insertDict 'b' 2 (insertDict 'a' (1::Int) emptyDict) $ 'a'
Just 1
Λ insertDict 'b' 2 (insertDict 'a' (1::Int) emptyDict) $ 'x'
Nothing
Representing maps as functions is good as a first approximation, but this representation has a number of drawbacks:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With