How to encode two distinct Unit types using church encoding - lambda-calculus

I was studying Haskell and happened to know the church encoding of algebraic data types. For example, the unit type in Haskell can be encoded as a polymorphic function type. But one can also define a Unit' type that is isomorphic to Unit but essentially treated as a distinct type from Unit. Then we have Unit :: Unit and Unit' :: Unit' as elements from different domains. How to do this in church encoding?
data Unit = Unit
type UnitChurch = forall x. x -> x
data Unit' = Unit'
type UnitChurch' = ?
I tried to search google for questions alike but did not find an answer. My guess is that maybe we can define UnitChurch' as:
type UnitChurch' = forall u. (UnitChurch -> u) -> u
which is similar to newtype in Haskell.

Related

Do any functional programming languages have syntax sugar for changing part of an object?

In imperative programming, there is concise syntax sugar for changing part of an object, e.g. assigning to a field:
foo.bar = new_value
Or to an element of an array, or in some languages an array-like list:
a[3] = new_value
In functional programming, the idiom is not to mutate part of an existing object, but to create a new object with most of the same values, but a different value for that field or element.
At the semantic level, this brings about significant improvements in ease of understanding and composing code, albeit not without trade-offs.
I am asking here about the trade-offs at the syntax level. In general, creating a new object with most of the same values, but a different value for one field or element, is a much more heavyweight operation in terms of how it looks in your code.
Is there any functional programming language that provides syntax sugar to make that operation look more concise? Obviously you can write a function to do it, but imperative languages provide syntax sugar to make it more concise than calling a procedure; do any functional languages provide syntax sugar to make it more concise than calling a function? I could swear that I have seen syntax sugar for at least the object.field case, in some functional language, though I forget which one it was.
(Performance is out of scope here. In this context, I am talking only about what the code looks like and does, not how fast it does it.)
Haskell records have this functionality. You can define a record to be:
data Person = Person
{ name :: String
, age :: Int
}
And an instance:
johnSmith :: Person
johnSmith = Person
{ name = "John Smith"
, age = 24
}
And create an alternation:
johnDoe :: Person
johnDoe = johnSmith {name = "John Doe"}
-- Result:
-- johnDoe = Person
-- { name = "John Doe"
-- , age = 24
-- }
This syntax, however, is cumbersome when you have to update deeply nested records. We've got a library lens that solves this problem quite well.
However, Haskell lists do not provide an update syntax because updating on lists will have an O(n) cost - they are singly-linked lists.
If you want efficient update on list-like collections, you can use Arrays in the array package, or Vectors in the vector package. They both have the infix operator (//) for updating:
alteredVector = someVector // [(1, "some value")]
-- similar to `someVector[1] = "some value"`
it is not built-in, but I think infix notation is convenient enough!
One language with that kind of sugar is F#. It allows you to write
let myRecord3 = { myRecord2 with Y = 100; Z = 2 }
Scala also has sugar for updating a Map:
ms + (k -> v)
ms updated (k,v)
In a language such as Haskell, you would need to write this yourself. If you can express the update as a key-value pair, you might define
let structure' =
update structure key value
or
update structure (key, value)
which would let you use infix notation such as
structure `update` (key, value)
structure // (key, value)
As a proof of concept, here is one possible (inefficient) implementation, which also fails if your index is out of range:
module UpdateList (updateList, (//)) where
import Data.List (splitAt)
updateList :: [a] -> (Int,a) -> [a]
updateList xs (i,y) = let ( initial, (_:final) ) = splitAt i xs
in initial ++ (y:final)
infixl 6 // -- Same precedence as +
(//) :: [a] -> (Int,a) -> [a]
(//) = updateList
With this definition, ["a","b","c","d"] // (2,"C") returns ["a","b","C","d"]. And [1,2] // (2,3) throws a runtime exception, but I leave that as an exercise for the reader.
H. Rhen gave an example of Haskell record syntax that I did not know about, so I’ve removed the last part of my answer. See theirs instead.

Concatenate 2 Enumerated type variable sets

enum sup;
sup=['a','b','c'];
enum sup2;
sup2=['d','e','f'];
enum sup3;
sup3=sup++sup2;
I want to get an new enumerated type sup3 with all a,b,c,d,e,f.Is there any way in minizinc we can do this.
The short answer is no, this is currently not supported. The main issue with the concatenation of enumerated types comes from the fact we are not just concatenating two lists of things, but we are combining types. Take your example:
enum sup = {A, B, C};
enum sup2 = {D, E, F};
enum sup3 = sup ++ sup2;
When I now write E somewhere in an expression, I no longer know if it has type sup2 or sup3. As you might imagine, there is no guarantee that E would have the same value (for the solver) in the two enumerated types, so this can be a big problem.
To shine a glimmer of hope, the MiniZinc team has been working on a similar approach to make this possible (but not yet formally announced). Instead of your syntax, one would write:
enum X = {A, B, C};
enum Y = {D, E, F} ++ F(X);
The idea behind this is that F(X) now gives a constructor for the usage of X in Y. This means that if we see just A, we know it's of type X, but if we see F(A), then it's of type Y. Again, this is not yet possible, but will hopefully end up in the language soon.
More of a comment but here is my example of my need. When doing code coverage and FSM transition analysis I am forced to use exclusion to not analyze some transitions for the return_to_state, in the code below. If instead I could use concatenated types as shown, I would have more control over the tools reporting missing transitions.
type Read_states is (ST1);
type Write_states is (ST2, ST3, ST4);
type SPI_states is (SPI_write);
type All_States is Read_states & Write_states & SPI_states;
I could make return_to_state of type Write_states and FRAM_state of type All_states and then not have to put in exclusions in my FSM analysis.

When generalizing monad, performance drops nearly 50%

I have code that does some parsing of files according to specified rules. The whole parsing takes place in a monad that is a stack of ReaderT/STTrans/ErrorT.
type RunningRule s a = ReaderT (STRef s LocalVarMap) (STT s (ErrorT String Identity)) a
Because it would be handy to run some IO in the code (e.g. to query external databases), I thought I would generalize the parsing, so that it could run both in Identity or IO base monad, depending on the functionality I would desire. This changed the signature to:
type RunningRule s m a = ReaderT (STRef s LocalVarMap) (STT s (ErrorT String m)) a
After changing the appropriate type signatures (and using some extensions to get around the types) I ran it again in the Identity monad and it was ~50% slower. Although essentially nothing changed, it is much slower. Is this normal behaviour? Is there some simple way how to make this faster? (e.g. combining the ErrorT and ReaderT (and possibly STT) stack into one monad transformer?)
To add a sample of code - it is a thing that based on a parsed input (given in C-like language) constructs a parser. The code looks like this:
compileRule :: forall m. (Monad m, Functor m) =>
-> [Data -> m (Either String Data)] -- For tying the knot
-> ParsedRule -- This is the rule we are compiling
-> Data -> m (Either String Data) -- The real parsing
compileRule compiled (ParsedRule name parsedlines) =
\input -> runRunningRule input $ do
sequence_ compiledlines
where
compiledlines = map compile parsedlines
compile (Expression expr) = compileEx expr >> return ()
compile (Assignment var expr) =
...
compileEx (Function "check" expr) = do
value <- expr
case value of
True -> return ()
False -> fail "Check failed"
where
code = compileEx expr
This is not so unusual, no. You should try using SPECIALIZE pragmas to specialize to Identity, and maybe IO too. Use -ddump-simpl and watch for warnings about rule left hand sides being too complicated. When specialization doesn't happen as it should, GHC ends up passing around typeclass dictionaries at runtime. This is inherently somewhat inefficient, but more importantly it prevents GHC from inlining class methods to enable further simplification.

How to iterate through a UTF-8 string correctly in OCaml?

Say I have some input word like "føøbær" and I want a hash table of letter frequencies s.t. f→1, ø→2 – how do I do this in OCaml?
The http://pleac.sourceforge.net/pleac_ocaml/strings.html examples only work on ASCII and https://ocaml-batteries-team.github.io/batteries-included/hdoc2/BatUTF8.html doesn't say how to actually create a BatUTF8.t from a string.
The BatUTF8 module you refer to defines its type t as string, thus there is no conversion needed: a BatUTF8.t is a string. Apparently, the module encourages you to validate your string before using other functions. I guess that a proper way of operating would be something like:
let s = "føøbær"
let () = BatUTF8.validate s
let () = BatUTF8.iter add_to_table s
Looking at the code of Batteries, I found this of_string_unsafe, so perhaps this is the way:
open Batteries
BatUTF8.iter (fun c -> …Hashtbl.add table c …) (BatUTF8.of_string_unsafe "føøbær")`
although, since it's termed "unsafe" (the doc's don't say why), maybe this is equivalent:
BatUTF8.iter (fun c -> …Hashtbl.add table c …) "føøbær"
At least it works for the example word here.
Camomile also seems to iterate through it correctly:
module C = CamomileLibraryDefault.Camomile
C.iter (fun c -> …Hashtbl.add table c …) "føøbær"
I don't know of the tradeoffs between Camomile and BatUTF8 here, though they end up storing different types (BatUChar vs C.Pervasives.UChar).

ML syntax function program

What could be the possible function foo, which has a type
’a * ’a -> int
in ML. i.e. a function which has the following type of the output
This seems to be homework, so I give you a partial solution and some hints only. The type you want is a 'a * 'a -> int, so the skeleton of a suitable function could be something like this (I assume you are using Standard ML):
fun foo(x, y) = ???
The ??? needs to meet two requirements: it must contain an expression that forces x and y to have the same type, and it must return an integer. The latter shouldn't be hard. For the former, there are many possibilities in SML, e.g., putting them in the same list, or returning them from the branches of the same if or case or handle.

Resources