multi-directional infinte sequence - ML - ml

I want to use the datatype sequence that is defined as follows:
datatype 'a seq = Nil | Cons of 'a * (unit-> 'a seq);
exception EmptySeq;
fun head(Cons(x,_)) = x | head Nil = raise EmptySeq;
fun tail(Cons(_,xf)) = xf() | tail Nil = raise EmptySeq;
which has to option to iterate over functions backward and forward:
datatype direction = Back | Forward;
datatype 'a bseq = bNil | bCons of 'a * (direction -> 'a bseq);
and i defined those as well:
fun bHead(bCons(x,_)) = x | bHead bNil = raise EmptySeq;
fun bForward(bCons(_,xf)) = xf(Forward) | bForward bNil = raise EmptySeq;
fun bBack(bCons(_,xf)) = xf(Back) | bBack bNil = raise EmptySeq;
Now, what I'm trying to do is to create a function "create_seq" that gets an int "k" and returns an infinte sequence which can be iterated back and forth.
for example:
- create_seq 2;
val it = bCons (2,fn) : int bseq
- bForward it;
val it = bCons (3,fn) : int bseq
- bForward it;
val it = bCons (4,fn) : int bseq
- bBack it;
val it = bCons (3,fn) : int bseq
- bBack it;
val it = bCons (2,fn) : int bseq
- bBack it;
val it = bCons (1,fn) : int bseq
- bBack it;
val it = bCons (0,fn) : int bseq
- bBack it;
val it = bCons (~1,fn) : int bseq
this is what I've been trying to do and can't figure out why it doesn't work:
fun create_seq k = (k,fun check Forward = create_seq(k+1)
| check Back = create_seq(k-1));
nor this:
fun create_seq k = (k,fn x => case x of Forward => create_seq(k+1)
| Back => create_seq(k-1));
or even this:
fun create_seq k = (k,fn Forward => create_seq(k+1)
| Back => create_seq(k-1));

It seems I forgot the constructor:
fun intbseq(k:int) = bCons(k,fn Forward => intbseq(k+1)| Back => intbseq(k-1));
this should work.

Related

Argument types problem ('float', 'const int') in array

I've been trying my first codes in pine script. The question is this. I have created few array.new_float to use as buffers in the 'for' statement. The thing is that I need to do some math over the data. Now, once the 'for' is done, an error pops: 'Cannot call 'operator -' with argument 'expr0' = 'High'.An argument of 'float[]' type was used but a 'const int' is expected'.
Please, if anyone knows what am I doing wrong, I will thank you.
Edit: I will leave the script of what I'm trying to do here
//#version=5
// Indicator name
indicator("DAF_Swing_Index", shorttitle= 'DAF_SwInd', overlay=false)
// Input
T = input.int(30000, title = 'Ratio de escala', minval = 1000, maxval = 150000)
Shift = input.int(0, title = 'Desplazamiento horizontal', minval = 0, maxval = 100)
// Array
SWINGINDEX = array.new_float(200)
Open = array.new_float(200)
Open1 = array.new_float(200)
Close = array.new_float(200)
Close1 = array.new_float(200)
High = array.new_float(200)
Low = array.new_float(200)
// Other variable
var float SwingIndex = 0
var int StartBars = 1
Prev_calculated = bar_index
Rates_total = bar_index + 1
var float SH1 = 0
var float SI = 0
var float R = 0
// Initial bar verification
if Rates_total < StartBars
SwingIndex := 0
Primero = 1
if Prev_calculated > Rates_total or Prev_calculated <= 0
Primero := 1
else
Primero := Prev_calculated-1
// Main process
for bar = Primero to Rates_total
array.push(Open, high[bar])
array.push(Open1, open[bar-1])
array.push(Close, close[bar])
array.push(Close1, close[bar-1])
array.push(High, high[bar])
array.push(Low, low[bar])
K = math.max(math.abs(High - Close1), math.abs(Low - Close1))
TR = math.max(math.max(math.abs(High-Close1), math.abs(Low-Close1)), math.abs(High-Low))
ER = 0.0
if Close1 > High
ER := math.abs(High - Close1)
if Close1 < Low
ER := math.abs(Low - Close1)
SH1 := math.abs(Close1 - Open1)
R := TR - 0.5 * ER + 0.25 * SH1
SI := 0.0
if R != 0
SI := 50 * ((Close - Close1) + 0.5 * (Close - Open1)) * (K / T) / R
SwingIndex := SI
// ploting result
plot(SwingIndex, title = 'Swing Index', style = plot.style_line, color = color.rgb(193, 255, 51, 10))
So, what the error message tells you is, your are passing an array, where it expects a const value.
Like here:
K = math.max(math.abs(High - Close1), math.abs(Low - Close1))
All those variables (High, Close1, Low) are arrays. It simply can not subtract one array from another. You can however, subtract one element from another element.
So for that line, I believe you want something like this:
K = math.max(math.abs(array.get(High, bar) - array.get(Close1, bar)), math.abs(array.get(Low, bar) - array.get(Close1, bar)))
With array.get(), you can get value the of the element at the specified index.
You should fix this in all other occurences.

Using Array.Count and match cases F#

I am not sure yet what the problem is, I am trying to go through a ResizeArray and matching the item with the data type, and depending on this, take away the value in a specific field (iSpace) from thespace(which is how much space the inventory has), before returning the final value.
A snippet of my code :
let spaceleft =
let mutable count = 0 //used to store the index to get item from array
let mutable thespace = 60 //the space left in the inventory
printf "Count: %i \n" inventory.Count //creates an error
while count < inventory.Count do
let item = inventory.[count]
match item with
|Weapon weapon ->
thespace <- (thespace - weapon.iSpace)
|Bomb bomb ->
thespace <-(thespace - bomb.iSpace)
|Potion pot ->
thespace <- (thespace - pot.iSpace)
|Armour arm ->
thespace <- (thespace - arm.iSpace)
count <- count+1
thespace
I get an error about Int32, that has to do with the
printf "Count: %i \n" inventory.Count
line
Another problem is that thespace doesn't seem to change, and always returns as 60, although I have checked and inventory is not empty, it always has at least two items, 1 weapon and 1 armour, so thespace should atleast decrease yet it never does.
Other snippets that may help:
let inventory = ResizeArray[]
let initialise =
let mutable listr = roominit
let mutable curroom = 3
let mutable dead = false
inventory.Add(Weapon weap1)
inventory.Add(Armour a1)
let spacetogo = spaceleft //returns 60, although it should not
Also, apart from the iniitialise function, other functions seem not to be able to add items to the inventory properly, eg:
let ok, input = Int32.TryParse(Console.ReadLine())
match ok with
|false ->
printf "The weapon was left here \n"
complete <- false
|true ->
if input = 1 && spaceleft>= a.iSpace then
inventory.Add(Weapon a)
printf "\n %s added to the inventory \n" a.name
complete <- true
else
printf "\n The weapon was left here \n"
complete <- false
complete
You have spaceLeft as a constant value. To make it a function you need to add unit () as a parameter. Here's that change including a modification to make it much simpler (I've included my dummy types):
type X = { iSpace : int }
type Item = Weapon of X | Bomb of X | Potion of X | Armour of X
let inventory = ResizeArray [ Weapon {iSpace = 2}; Bomb {iSpace = 3} ]
let spaceleft () =
let mutable thespace = 60 //the space left in the inventory
printf "Count: %i \n" inventory.Count
for item in inventory do
let itemSpace =
match item with
| Weapon w -> w.iSpace
| Bomb b -> b.iSpace
| Potion p -> p.iSpace
| Armour a -> a.iSpace
thespace <- thespace - itemSpace
thespace
spaceleft () // 55
The above code is quite imperative. If you want to make it more functional (and simpler still) you can use Seq.sumBy:
let spaceleft_functional () =
printf "Count: %i \n" inventory.Count
let spaceUsed =
inventory
|> Seq.sumBy (function
| Weapon w -> w.iSpace
| Bomb b -> b.iSpace
| Potion p -> p.iSpace
| Armour a -> a.iSpace)
60 - spaceUsed
Just adding to the accepted answer: you can also match against record labels, as long as your inner types are records. Combine with an intrinsic type extension on the outer DU:
type X = { iSpace : int }
type Y = { iSpace : int }
type Item = Weapon of X | Bomb of Y | Potion of X | Armour of X
let inventory = ResizeArray [ Weapon {iSpace = 2}; Bomb {iSpace = 3} ]
let itemSpace = function
| Weapon { iSpace = s } | Bomb { iSpace = s }
| Potion { iSpace = s } | Armour { iSpace = s } -> s
type Item with static member (+) (a, b) = a + itemSpace b
60 - (Seq.fold (+) 0 inventory)
// val it : int = 55
Otherwise, you could resort to member constraint invocation expressions.
let inline space (x : ^t) = (^t : (member iSpace : int) (x))

Second argument replacing first scala

I am trying to define a function in scala ( ^ ), which takes 2 values and prints them like
2
x
Here is what I have so far...
class $ (val text2D: Array[Array[Char]])
{
def ^(that: $) =
{
" " ++ s"${this.text2D(0)(0)}" ++
"\n" ++ s"${that.text2D(0)(0)}"
}
def +(that: $) = this.text2D + "+" + that.text2D
override def toString = s"${this.text2D(0)(0)}"
}
object $ {
val array = Array.ofDim[Char](1,1)
def apply(x: String): $ = {
array (0)(0) = x.charAt(0)
new $ (array)
}
}
val x = $("x")
println(x)
val x2 = $("x") ^ $("2")
println(x2)
When I run this, I do not get the output I am expecting, instead I get
2
2
Why is it only taking the second element? Any help would be appreciated.
object creates a singleton, so the (mutable) array that you use is shared between calls to apply. You need to allocate that array inside the apply call.
def apply(x: String): $ = {
val array = Array.ofDim[Char](1,1)
array (0)(0) = x.charAt(0)
new $ (array)
}
Also, slightly unrelated, but I believe you have your arguments backward. To get the output you want, you need
" " ++ s"${that.text2D(0)(0)}" ++
"\n" ++ s"${this.text2D(0)(0)}"
I think what you need is something like this:
class $(val text2D: Array[String]) {
def ^(that: $): $ = {
if (this.text2D.length == 0)
that
else if (that.text2D.length == 0)
this
else {
val thisW = this.text2D(0).length
val thatW = that.text2D(0).length
// cross-pad arrays to have the same width
val padThisRight = " " * thatW
val padThatLeft = " " * thisW
val thisPaddedW = this.text2D.map(_ + padThisRight)
val thatPaddedW = that.text2D.map(padThatLeft + _)
// first lines comes from that!
new $(thatPaddedW ++ thisPaddedW)
}
}
def +(that: $): $ = {
if (this.text2D.length == 0)
that
else if (that.text2D.length == 0)
this
else {
val thisH = this.text2D.length
val thatH = that.text2D.length
val thisW = this.text2D(0).length
val thatW = that.text2D(0).length
// pad arrays to have the same height
val emptyThis = " " * thisW
val emptyThat = " " * thatW
val thisPaddedH = if (thisH >= thatH) this.text2D else Array.fill(thatH - thisH)(emptyThis) ++ this.text2D
val thatPaddedH = if (thisH <= thatH) that.text2D else Array.fill(thisH - thatH)(emptyThat) ++ that.text2D
new $(thisPaddedH.zip(thatPaddedH).map(p => p._1 + p._2))
}
}
override def toString = text2D.mkString("\n")
}
object $ {
def apply(x: String): $ = {
new $(Array[String](x))
}
}
and then
val x2 = $("x") ^ $("2")
println(s"x2:\n$x2")
println("----------------------------")
val z = x2 + $(" + ") + y2
println(s"z:\n$z")
println("----------------------------")
val zz = x2 + $(" + ") + (y2 ^ $("3"))
println(s"zz:\n$zz")
println("----------------------------")
produces following output
x2:
2
x
----------------------------
z:
2 2
x + y
----------------------------
zz:
3
2 2
x + y
----------------------------
The main idea here is that operations on $ produce another instance of $ rather than String (I use String instead of Array[Char] as it seems much easier and has no obvious drawbacks). In such way you don't have to re-parse String splitting it by new lines and have to wonder how to handle cases when the string is not well-aligned. So now operators ^ and + is just an exercise in aligning two 2d-arrays to have either the same width or the same height and then joining them.

ML can't unify 'a with int

The exercise is to code a function in ML that deletes an element from a binary search tree.
Here's the code:
datatype 'a tree = Lf | Br of 'a * 'a tree * 'a tree;
fun deleteTop (Br(_, Lf, t2)) = t2
| deleteTop (Br(_, t1, Lf)) = t1
| deleteTop (Br(_, Br(v, u1, u2), t2)) =
Br(v, deleteTop (Br(v, u1, u2)), t2);
fun delete (Lf, k : string) = Lf
| delete (Br((a,b),t1,t2), k) =
if a=k then deleteTop(Br((a,b),t1,t2))
else if k<a then Br((a,b),delete(t1,k),t2)
else Br((a,b),t1,delete(t2,k));
When I load this into Poly/ML it warns me of incomplete pattern matching in deleteTop but that doesn't matter because delete only ever passes deleteTop a branch.
val deleteTop = fn: 'a tree -> 'a tree
val delete = fn: (string * 'a) tree * string -> (string * 'a) tree
I created a (string * int) tree and ran
> delete(a,"they");
Error-Type error in function application.
Function: delete : (string * 'a) tree * string -> (string * 'a) tree
Argument: (a, "they") : (string * int) tree * string
Reason:
Can't unify (string * 'a) tree with (string * int) tree
(Different type constructors)
Found near delete (a, "they")
Static Errors
Let me re-iterate one of those lines:
Can't unify (string * 'a) tree with (string * int) tree
Why can't ML unify 'a with int?
You can get a message like that if you have redefined tree and delete at the top level since you defined a. It's complaining that the tree in a is not the same as the tree in delete.
For example
> datatype 'a t = T of 'a;
datatype 'a t = T of 'a
> val x = T 1;
val x = T 1: int t
> datatype 'a t = T of 'a;
datatype 'a t = T of 'a
> val T y = x;
Pattern and expression have incompatible types.
Pattern: T y : 'a t
Expression: x : int t
Reason: Can't unify 'a t with int t (Different type constructors)
Found near val T y = x
Static Errors
>

How to use a self made Type in F#?

I made a type, but I don't know how to use it properly and I don't found any solution on google.
type Sample =
{
TrackPosition : int
TubePosition : int
Barcode : string
}
let arraySamples = Array.create Scenario.Samples.NumberOfSamples **Sample**
BarcodeGenerieren.Samples.Sample
let mutable trackPosition = Scenario.Samples.StartTrackPositions
let mutable index = 1
for i in 1 .. Scenario.Samples.NumberOfSamples do
let randomNumber = System.Random().Next(0,9999)
if index > 24 then
trackPosition <- trackPosition + 1
index <- 1
arraySamples.[index] <- **new Sample{TrackPosition= trackPosition, TubePosition = index, Barcode = sprintf "100%s%06d" ((trackPosition + 1) - Scenario.Samples.StartTrackPositions) randomNumber}**
So my question is, what should I changed so that it works, when I will give the type of the array and when I will give the sample with data to the array?
You have created what is referred to as a record type. You can initialise it with the following syntax
{TrackPosition = 0;TubePosition = 0;Barcode = "string"}
your syntax in the last line is almost correct - it should be
arraySamples.[index] <- Sample{
TrackPosition= trackPosition;
TubePosition = index;
Barcode = sprintf "100%s%06d" ((trackPosition + 1) - Scenario.Samples.StartTrackPositions) randomNumber}
The changes are
Eliminate new
replace , with ;

Resources