Queues in Ocaml - enq - algorithm

I can't seem to get my code working enq. How am I supposed to declare the queue datattype as well?
let enq (q, x) =
match q with
queue ([], b) -> queue([], x::b)
| queue (f, []) -> queue(f, [x])
| queue (f, b) -> queue(f, x::b);;

You need to distinguish between the name of the type and the constructor names used to make elements of the type. For your code, the type name could be queue (type names begin with lower case) and you could have just a single constructor named Queue (constructors begin with upper case).
The type declaration would look like this then:
type 'a queue = Queue of 'a list * 'a list
Note that this type is parameterized by the type of the elements of the queue (denoted as 'a in the declaration).
In your code, the pattern matches should be against the constructor Queue, not against the type name queue.
I would also say as a side comment that all the cases in your code look the same to me. I suspect there might be just one case.

Related

Inline records in polymorphic variants?

The ocaml manual chapter 8 "language extensions" describes "inline records" (8.17):
The arguments of sum-type constructors can now be defined using the same syntax as records. Mutable and polymorphic fields are allowed. GADT syntax is supported. Attributes can be specified on individual fields. [...]
I am looking for that with polymorphic variants:
# type a = B of {x:int; mutable y:int} ;;
type a = B of { x : int; mutable y : int; }
# type b = `A of {u:int; mutable v:int} ;;
Line 1, characters 9-10:
Error: Syntax error
But that does not work, so right now I use an explicit auxiliary record type instead...
As I understand it now, this both takes more memory and is somewhat slower.
Can I get this cool feature with polymorphic variants, too?
In the cases of ordinary constructors, the compiler can use the type definition to distinguish between:
type t = A of int * int | B
let f = function
| A (_,y) -> y
| B -> 0
and
type 'a t = A of 'a | B
let f = function
| A (_,y) -> y
| B -> 0
Thus, it is possible to optimize the first
A (_,y) -> y
into "access the second field of the block` while still compiling the second case
A (_,y) -> y
to "access the tuple in the first field of the block, and then access the second field of the block".
For polymorphic variants, it is not possible to rely on the non-existing type definition to distinguish between those two solutions. Consequently, their memory representation must be uniform. This means that polymorphic variants always take one argument, and it is not really useful to label each argument of the constructor when there is only one argument.
This is why inline records cannot be combined with polymorphic variants.

meaning of this ocaml syntax

I'm reading lambdasoup/soup.ml at master · aantron/lambdasoup · GitHub but I don't understand the syntax.
and 'a node =
{mutable self : 'b. 'b node option;
mutable parent : general node option;
values : [ `Element of element_values
| `Text of string
| `Document of document_values ]}
I don't understand 'b. 'b node option, if it was * it would be a tuple but it's the first time I see with . Also why the back-tic in the branches (e.g. `Element)?
The type 'a . type is a type that is explicitly polymorphic in 'a. So your example 'b . 'b node option is explcitly a field whose contents are polymorphic. In other words, any value assigned to the field must itself be polymorphic.
Here's an example with list rather than node:
type a = { mutable self : 'b. 'b list option; }
# let x = { self = None };;
val x : a = {self = None}
# x.self <- None;;
- : unit = ()
# x.self <- Some [];;
- : unit = ()
# x.self <- Some [3];;
Error: This field value has type int list option
which is less general than 'b. 'b list option
#
You can assign None to x.self because None is polymorphic (its type is 'a option, which works for any option type). You can assign Some [] to x.self because it's also polymorphic (its type is 'a list option, which works for any optional list). But you can't assign Some [3] to x.self because its type is int list option; in other words, it's not polymorphic.
You can find a discussion of explicitly polymorphic types in Section 5.2.1 of the OCaml manual.
Variant values with leading backquote like `A or `B are so-called polymorphic variants. This is a different feature than the usual variant types. The basic idea is that a polymorphic variant represents a value that is not necessarily part of any predefined type. The associated types are essentially sets of these values. Polymorphic variants can also be constructors as in your example type; that is, they can take an associated value. Just as you can have Some "yes", your definition allows one to have `Text "yes".
You can find some discussion of polymorphic variants in Section 7.4 of the OCaml manual (search for "polymorphic variant types").

Scala Tree/Graph Implementation

I have a problem about a "customer invitation" where a person can invite another person and the invitation is only valid if the invited person invitee someone.
To solve this problem, i was thinking to write a Tree algorithm instead a Graph algorithm.
I'm trying to write this tree structure in Scala and here is how i've started:
case class MyNode(key:Int, children:Option[List[MyNode]] = None)
class MyNodeManager {
def find(key: Int, tree: Option[List[MyNode]]) = tree match {
case None => None
case (h :: t) =>
println("aa")
/*if(h.key == key)
Option(h)
else
find(h ::: t)
*/
}
}
The input will be something like:
val invites = List((1, 2), (1, 3), (3, 6))
I would like to work with Option[List[MyNode]] because children are option and if the node has been invited, i would like to set value an empty list instead None.
Tree is the best structure to solve my problem or should i go to Graph or something like that (a node in a graph can have multiple children?)? And the other question..what's the difference on those lines (h :: t) and (h ::: t)?
The following code has a compile error:
Error:(16, 13) constructor cannot be instantiated to expected type;
found : scala.collection.immutable.::[B]
required: Option[List[MyNode]]
case (h :: t) =>
^
How can i work with Option[List]?
Should be
def find(key: Int, tree: Option[List[MyNode]]) = tree match {
case None => None
case Some(h :: t) =>
println("aa")
/*if(h.key == key)
Option(h)
else
find(h ::: t)
*/}
You are match Option object not tuple.
This match is not exhaustive because you are missing
case Some(Nil) => ....
I find it will be better to use only list without Optional. This is mostly about semantic. Optional means something is empty. We have value for empty list (Nil) so we don't need to use additional object to mark such situation. Empty list should be enough
::: function adds the elements of a given list in front of your list. Simply this function is used to concatenate two list
:: is function which add element at the begging of the list.
Also in Scala :: is a case class which have head and tail. If you want to know more about List implementation I suggest you to read https://www.amazon.com/Functional-Programming-Scala-Paul-Chiusano/dp/1617290653

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.

How to sort the list by its accountID using quick sort in Haskell

Im a student who is really new to functional programming. Im working on a banking application where the data has been already defined as,
type Accountno = Int
data Accounttype = Saving | Current | FixedDeposit deriving (Show,Read)
type Accountamount = Int
type Name = String
type Account = (Accountno, Name, Accounttype, Accountamount)
exampleBase :: [Account]
exampleBase = [ (1,"Jennifer",Saving,1000 ) ,
(5,"Melissa",Current,3000) ,
(2,"Alex",Saving,1500)]
Im trying to sort the list by its account number using the following code,
sortByID :: (Ord a) => [a] -> [a]
sortByID [] = []
sortByID (l :ls) =
let
smallerSorted = sortByID [x | x <- ls, x <= l]
biggerSorted = sortByID [x | x <- ls, x > l]
in
smallerSorted ++ [l] ++ biggerSorted
viewSortedDetails :: IO()
viewSortedDetails =
do
putStrLn "Account Details Sorted By Account ID"
let records = sortByID exampleBase
let viewRecord = map show records
mapM_ putStrLn viewRecord
But I do not get the expected result. as it gives me an error, informing "Instance of Ord Accounttype required for definition of viewSortedDetails".Please can some one help me to overcome this problem
Thanks a lot!
Well, the problem is that you're using ordering comparisons, such as <=, on two Account values, which would require Account to be an instance of Ord. Now, Account is a synonym for a four-element tuple, which are defined to be instances of Ord when all the types in the tuple are. Accountno, Name, and Accountamount are all synonyms for types with Ord instances, but Accounttype is not.
You could make it possible to sort Account values directly by making Accounttype an instance of Ord, which you can do by simply adding it to the deriving clause.
However, if you want to specifically sort only by the account number, not the other elements of the tuple, you'll need to do something differently. One option would be to make Account a data type with a custom Ord instance:
data Account = Account Accountno Name Accounttype Accountamount deriving (Eq, Show, Read)
instance Ord Account where
(...)
Then you can define the ordering however you like.
Alternatively, you can leave it as is and instead only compare the element you want instead of the entire Account value, using something like this:
accountNo :: Account -> Accountno
accountNo (n,_,_,_) = n
...and then doing the comparison with something like smallerSorted = sortByID [x | x <- ls, accountNo x <= accountNo l]. The standard libraries also include a function on for this purpose, but it would awkward to use in this case.
A few other remarks, which are less relevant to your question, on the general subject of Haskell code:
Defining Account as a data type, probably using the record syntax, would be nicer than using a type synonym here. Large tuples can be awkward to work with.
Accountno and Accountamount should probably be different types as well, to avoid mixing them with other Ints: the first because doing arithmetic on account numbers makes little sense, the latter in part because (I'm guessing) you're implicitly using fixed point arithmetic, such that 100 actually means 1.00, and in general just to avoid confusion.
In fact, Int is probably a bad choice for Accountamount anyway: Why not something from Data.Fixed, Ratio Integer, or a base-10-safe floating point type (although there isn't one in the standard libraries, unfortunately).
The standard libraries of course include sorting functions already--I'm assuming the reimplementation is for learning purposes, but in practice it could all be replaced by something like sortBy (compare `on` accountNo).

Resources