F# record and evaluating of this - syntax

I'm struggling a bit with a F#-assignment, which I hope you can answer for mere: I have that
We will use the type OrderedList<’a> declared as follows
type OrderedList<’a when ’a : equality> =
{ front: ’a list
; rear: ’a list}
For instance, the value let ex = {front = [’x’]; rear = [’z’;’y’]} has
type OrderedList<char> and represents the ordered list [’x’, ’y’, ’z’].
The question that I'm struggling with is:
We define the canonical representation of an ordered list to be the
representation where the rear list is empty. Declare a function
canonical:OrderedList<’a>->OrderedList<’a>, where canonical ol returns
the canonical representation of ol.
Just as a startup, I've tried something:
let canonicial (list:OrderedList<'a>)=
match list with
| {x::xs}, {y::xss} -> if x = y then "SUCCESS!!!!" else failwith "FEJL!!!"
| _ -> failwith "Some"
My issue is that I don't know how to get to the element in the type / the syntax for this. I know the function has not been solved correctly, but right now I focus mostly on the syntax.
Hope to get some help!

Well I think I can give you the solution now (you surely have more problems to solve):
let canonical =
function
| { front = _; rear = [] } as ol -> ol
| { front = fs; rear = rs } -> { front = fs # List.rev rs; rear = [] }
as you can see the first case is when the rear is already empty - here it's enough to give to original back
in the other case we have to get a new OrderedList<'a> with the reversed old rear appended to the old front - that's it - you don't even need the constraint on 'a - and indeed I find it strange to put it there - usually it's better to but the constraints on the functions in FP - but well different styles and stuff.
I hope this helps you out a bit
BTW: I used function on purpose - you should try to convert this into your usual match ... with ... style so you can get your syntax right

Thanks, thanks, thanks! Now I better understand this topic! I rewritten your code to:
let canonical2 (ol:OrderedList<'a>) : OrderedList<'a> =
match ol with
|{ front = _; rear = []} -> ol
|{ front = f; rear = r} -> {front = f # List.rev r; rear = []}

Another way to do it granted that # already takes care of returning the "other list" if one is empty (so shouldn't be an overhead to always append) :
let canonical ol = { ol with front = ol.front # List.rev ol.rear; rear = [] }
// or
let canonical { front = fs; rear = rs } = { front = fs # List.rev rs; rear = [] }

Related

Answering the Longest Substring Without Repeating Characters in Kotlin

I've spend some time working on the problem and got this close
fun lengthOfLongestSubstring(s: String): Int {
var set = HashSet<Char>()
var initalChar = 0
var count = 0
s.forEach {r ->
while(!set.add(s[r]))
set.remove(s[r])
initalChar++
set.add(s[r])
count = maxOf(count, r - initialChar + 1)
}
return count
}
I understand that a HashSet is needed to answer the question since it doesn't allow for repeating characters but I keep getting a type mismatch error. I'm not above being wrong. Any assistance will be appreciated.
Your misunderstanding is that r represents a character in the string, not an index of the string, so saying s[r] doesn't make sense. You just mean r.
But you are also using r on its own, so you should be using forEachIndexed, which lets you access both the element of the sequence and the index of that element:
s.forEach { i, r ->
while(!set.add(r))
set.remove(r)
initialChar++
set.add(r)
count = maxOf(count, i - initialChar + 1)
}
Though there are still some parts of your code that doesn't quite make sense.
while(!set.add(r)) set.remove(r) is functionally the same as set.add(r). If add returns false, that means the element is already in the set, you remove it and the next iteration of the loop adds the element back into the set. If add returns true, that means the set didn't have the element and it was successfully added, so in any case, the result is you add r to the set.
And then you do set.add(r) again two lines later for some reason?
Anyway, here is a brute-force solution that you can use as a starting point to optimise:
fun lengthOfLongestSubstring(s: String): Int {
val set = mutableSetOf<Char>()
var currentMax = 0
// for each substring starting at index i...
for (i in s.indices) {
// update the current max from the previous iterations...
currentMax = maxOf(currentMax, set.size)
// clear the set to record a new substring
set.clear()
// loop through the characters in this substring
for (j in i..s.lastIndex) {
if (!set.add(s[j])) { // if the letter already exists
break // go to the next iteration of the outer for loop
}
}
}
return maxOf(currentMax, set.size)
}

CodeQL "otherwise"-ish construct?

I'm new to CodeQL, and still trying to wrap my head around it. On a semi-frequent basis, I find myself wanting for a language construct that supports specifying a "fallback value", to implement the following logic:
foot Foo(...) {
result = A
or
not eists(foot t | t = A) and
result = B
or
not eists(foot t | t = A) and
not eists(foot t | t = B) and
result = C
}
// aka
foot Foo(...) {
if eists(foot t | t = A) then
result = A
else if eists(foot t | t = B) then
result = B
else
result = C
}
Does CodeQL provide a way to rephrase this in a more elegant way? I've browsed the docs over and over again for something like the following, but to no avail:
foot Foo(...) {
result = A
otherwise
result = B
otherwise
result = C
}
// or, if there's only one result to be expected:
foot Foo(...) {
result = first([ A, B, C ])
}
I feel like my little imperative programmer's brain must be missing something that's been staring at my face the whole time.
At the moment there does not seem to be such language construct. There are however discussions for requesting this (or similar) features (#5348, #5573).
Note that in your example code you could simplify your exists(foot t | t = A) to just exists(A).

Why is it so slow to create records with a field that references a big value in F#?

In the code below that is executed as an .fsx script, the final line takes around 30 seconds to finish. I assumed that since records are reference types, the final line only creates records with a field that references an (immutable) large value, and so it should be very fast. Why is it slow and how can I fix it?
type BigType = { Big: Set<int> }
type CollectionType = { BigVal: BigType; SmallVal: int }
let b = { Big = set [ 0 .. 999999 ] }
let mySet = set [ 0 .. 50 ]
#time
mySet |> Set.map (fun x -> { BigVal = b; SmallVal = x })
Thank you.
One thing to notice here is that the order you define the fields in type CollectionType = { BigVal: BigType; SmallVal: int } makes a difference. If you try:
type BigType = { Big: Set<int> }
type CollectionType = { SmallVal: int; BigVal: BigType; }
let b = { Big = set [ 0 .. 999999 ] }
let mySet = set [ 0 .. 50 ]
#time
mySet |> Set.map (fun x -> { BigVal = b; SmallVal = x })
Instead the time taken goes from Real: 00:00:34.385 to Real: 00:00:00.002.
NB: I was originally concerned that this behaviour could not be relied on and might change without warning; however as nasosev has found this behaviour is described in the F# language specification see section 8.15.3 of version 4.1 of the document.
The reason is that Set is implemented as a search tree, so in order to insert an item into a set, it is compared against some of the existing items. So there are indeed only small records created, but whole sets are being compared.
It's hard to tell what the best way to fix the issue is without knowing the exact problem you're solving. But if it is a requirement that each CollectionType value has a different SmallVal, then you can do as Scott suggests and implement custom comparison that only looks at SmallVal. You don't need a class though, you can do it with a record:
(* For records, you need to put CustomComparison in addition to implementing IComparable.
And CustomComparison requires CustomEquality and its corresponding overrides. *)
[<CustomComparison; CustomEquality>]
type CollectionType =
{ BigVal: BigType; SmallVal: int }
interface System.IComparable with
member this.CompareTo(that) =
match that with
| :? CollectionType as that -> compare this.SmallVal that.SmallVal
| _ -> -1
override this.Equals(that) =
match that with
| :? CollectionType as that -> this.SmallVal = that.SmallVal
| _ -> false
override this.GetHashCode() = this.SmallVal
If you convert to an array first then it takes no time at all:
mySet |> Set.toList |> List.map (fun x -> { BigVal = b; SmallVal = x })
So the time that it take to create the records is insignificant. The reason it's slow is that the records are inside a set. Sets need to compare their items to each other as part of the implementation, to make sure there are no duplicate values. F# compares records structurally, by comparing their contents. So these records that are being compared contain very large sets that take a long time to compare. They are actually different records but the same set in terms of objects in memory, but the F# record comparison doesn't know that, and doesn't check.
Welcome to the F# community.
I'm guessing that each new record is copying b, although since records are reference types by default, as you say, I'm not sure why that would be.
This approach is no faster:
let y = { BigVal = b; SmallVal = 0 }
mySet |> Set.map (fun x -> { y with SmallVal = x })
Using a class instead is much faster:
type BigType = { Big: Set<int> }
let b = { Big = set [ 0 .. 999999 ] }
type CollectionType(smallVal: int) =
interface System.IComparable with
member __.CompareTo other =
compare __.SmallVal (other :?> CollectionType).SmallVal
member __.BigVal = b
member __.SmallVal = smallVal
let mySet = set [ 0 .. 50 ]
#time
mySet |> Set.map (fun x -> CollectionType(x))
This is not a complete solution, since there is a warning FS0343: The type 'CollectionType' implements 'System.IComparable' explicitly but provides no corresponding override for 'Object.Equals'. An implementation of 'Object.Equals' has been automatically provided, implemented via 'System.IComparable'. Consider implementing the override 'Object.Equals' explicitly.

Implementation of a circular doubly linked list in OCaml

I am attempting to implement a circular doubly linked list using OCaml type declaration. Here is what I have :
type 'a cList =
{
mutable value : 'a;
mutable left : 'a cList option;
mutable right : 'a cList option
}
;;
The problem comes up when I need to declare a first list containing a single element. Because the element cannot be referenced before being assigned, I cannot get the left and right members of the cell to point on itself.
The only workaround I have so far is to allow the left and right members to be of type option, set them to None and then modify them so that they point on the cell itself.
let unitClist v = let a = {
value = v;
left = None;
right = None
}
in
a.left <- Some a;
a.right <- Some a;
a
;;
It works, but it is a bit binding to have to work with the option type when you are sure to have a value.
Is there a better way to do it ?
Thanks in advance.
Apparently you can also define a recursive value directly with a record. By using a rec binding you can refer to the binding recursively in the definition (in certain cases):
type 'a cList = {
mutable value : 'a;
mutable left : 'a cList;
mutable right : 'a cList
}
let unitClist v =
let rec a = {
value = v;
left = a;
right = a
}
in a
This is documented in Chapter 8.1 of the OCaml Manual
You could use objects instead, which are late binding and therefore allow self-reference:
object(self)
method value = v
method left = self
method right = self
end
There's a performance cost to this, of course, because all method calls will be dispatched dynamically, but this wouldn't be possible otherwise so that's the essential trade-off. You can't reference something that doesn't yet exist without employing some kind of indirection (edit: which a heap-allocated record already is. See my other answer).

Scrambled looking records in F#-Interactive

When trying to print
pop
I get all this weird looking formatting in F# interactive, which basically turns the printing useless. Is there someway other to correctly format this?
The code is the following:
#light
open System
let rng = new Random()
type Individual = { x:int; y:int }
type ScoredIndividual = { individual:Individual; score:int }
let genGene() = rng.Next(-10, 10)
let genRandInd() = { x=genGene(); y=genGene() }
let genRandPop popSize = [ for _ in 1 .. popSize -> genRandInd() ]
let getScoredPop f pop = List.map (fun i -> { individual=i; score=(f i)}) pop
let fitnessFun ind = ind.x * ind.x + ind.y * ind.y
let pop = 30 |> genRandPop |> getScoredPop fitnessFun
You can override ToString or use StructuredFormatDisplayAttribute to customize the string representation. This article contains some useful information about customizing output in fsi.
you might want to do fsi.AddPrinter for your ScoredIndividual type to control what's written to the console
That's pretty rough, and I couldn't find any "easy" way to fix it. However, FsEye can make it nicer (while it does delete the newlines, those spaces are in there good):

Resources