Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions as types in haskell

Tags:

haskell

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.

like image 459
user7235699 Avatar asked Feb 24 '18 11:02

user7235699


People also ask

Does every Haskell function have a type?

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.

How are functions defined in Haskell?

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.

What are type operators Haskell?

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).


1 Answers

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:

  • The complexity of searching for a value is linear in the number of keys.
  • Functions are pretty "opaque", which means you can't inspect or serialize the map as you could do if you had used a data type.
like image 126
danidiaz Avatar answered Oct 23 '22 15:10

danidiaz