Remove ifs from Javascript code - functional-programming

Can i program without if statements in functional programming in JS?
In Haskell you can do pattern matching:
sign x | x > 0 = 1
| x == 0 = 0
in js:
sing = x => {
if (x > 0) return 1;
else if (x == 0) return 0
}
I can do shorthand if operator something like this:
sign = x => x > 0 ? 1 (x == 0 ? 0 : x)
Can I make the code shorter without library and ?: operator above ?

This might not be the answer your looking for but the shortest way to write this code is:
return !!x+0;
explanation
!!x casts x to a boolean: x>0 == true x = 0 == false;
+0 casts to integer: true = 1, false = 0.
But no there is no other style than using ?: operator.
javascript shorthand usefullness
In javascript you have other helpful tricks like:
Automatically casting things to thruties or falsies. (when boolean required)
Or operator returning the value, easy for null coalescing: var name = null || 'joel' // name = 'joel'

Related

prove decreases clause of mutually recursive class functions

I'm having trouble showing how to ensure recursively decreasing functions on a tree class in Dafny. I have the following definitions which verify.
class RoseTree {
var NodeType: int
var id: string
var children: array<RoseTree>
ghost var nodeSet: set<RoseTree>
constructor(nt: int, id: string, children: array<RoseTree>)
ensures forall x :: 0 <= x < children.Length ==> children[x].nodeSet <= this.nodeSet
ensures forall x :: 0 <= x < this.children.Length ==> this.children[x].nodeSet <= this.nodeSet
{
this.NodeType := nt;
this.id := id;
this.children := children;
if children.Length == 0 {
this.nodeSet := {this};
}else{
this.nodeSet := {this}+childrenNodeSet(children);
}
}
}
function setRosePick(s: set<set<RoseTree>>): set<RoseTree>
requires s != {}
{
var x :| x in s; x
}
function setUnion(setosets: set<set<RoseTree>>) : set<RoseTree>
decreases setosets
{
if setosets == {} then {} else
var x := setRosePick(setosets);
assert x <= x + setUnion(setosets-{x});
x + setUnion(setosets-{x})
}
lemma setUnionDef(s: set<set<RoseTree>>, y: set<RoseTree>)
requires y in s
ensures setUnion(s) == y + setUnion(s - {y})
{
var x := setRosePick(s);
if y == x {
}else{
calc {
setUnion(s);
==
x + setUnion(s - {x});
== {setUnionDef(s - {x}, y); }
x + y + setUnion(s - {x} - {y});
== { assert s - {x} - {y} == s - {y} - {x}; }
y + x + setUnion(s - {y} - {x});
== {setUnionDef(s - {y}, x); }
y + setUnion(s - {y});
}
}
}
lemma setUnionReturns(s: set<set<RoseTree>>)
ensures s == {} ==> setUnion(s) == {}
ensures s != {} ==> forall x :: x in s ==> x <= setUnion(s)
{
if s == {} {
assert setUnion(s) == {};
} else {
forall x | x in s
ensures x <= setUnion(s)
{
setUnionDef(s, x);
assert x <= x + setUnion(s-{x});
}
}
}
function childNodeSets(children: array<RoseTree>): set<set<RoseTree>>
reads children
reads set x | 0 <= x < children.Length :: children[x]
{
set x | 0 <= x < children.Length :: children[x].nodeSet
}
function childNodeSetsPartial(children: array<RoseTree>, index: int): set<set<RoseTree>>
requires 0 <= index < children.Length
reads children
reads set x | index <= x < children.Length :: children[x]
{
set x | index <= x < children.Length :: children[x].nodeSet
}
function childrenNodeSet(children: array<RoseTree>): set<RoseTree>
reads children
reads set x | 0 <= x < children.Length :: children[x]
ensures forall x :: x in childNodeSets(children) ==> x <= childrenNodeSet(children)
ensures forall i :: 0 <= i < children.Length ==> children[i].nodeSet <= childrenNodeSet(children)
{
var y := childNodeSets(children);
setUnionReturns(y);
setUnion(y)
}
In particular I'm trying to define the height function for the tree.
function height(node: RoseTree):nat
reads node
reads node.children
reads set x | 0 <= x < node.children.Length :: node.children[x]
decreases node.nodeSet
{
if node.children.Length == 0 then 1 else 1 + maxChildHeight(node, node.children,node.children.Length-1,0)
}
function maxChildHeight(node: RoseTree, children: array<RoseTree>, index: nat, best: nat) : nat
reads node
reads node.children
reads set x | 0 <= x < node.children.Length :: node.children[x]
requires children == node.children
requires 0 <= index < children.Length
ensures forall x :: 0 <= x <= index < children.Length ==> maxChildHeight(node, children, index, best) >= height(children[x])
decreases node.nodeSet - setUnion(childNodeSetsPartial(children, index)), 1
{
if index == 0 then best else if height(children[index]) >= best then maxChildHeight(node, children, index-1, height(children[index])) else maxChildHeight(node, children, index-1, best)
}
I though it should be possible to show that the nodeSet of the node will be a subset of its parent node or that the union of child node sets will be a subset of the parent node, and thus both functions will terminate. My decreases expressions don't prove it to dafny and I'm not quite sure how to proceed. Is there another way to prove termination or can I fix these decrease statements?
Also, do all instances of a class have the constructor ensure statements applied implicitly or only if explicitly constructed using the constructor?
Edit: updated definitions of childNodeSetsPartial and maxChildHeight
to recurse downward. It still doesn't verify.
Defining mutable linked heap-allocated data structures in Dafny is not very common except as an exercise. So you should consider whether a datatype would serve you better, as in
datatype RoseTree = Node(children: seq<RoseTree>)
function height(r: RoseTree): int
{
if r.children == [] then
1
else
var c := set i | 0 <= i < |r.children| :: height(r.children[i]);
assert height(r.children[0]) in c;
assert c != {};
SetMax(c) + 1
}
If you insist on mutable linked heap-allocated data structures, then there is a standard idiom for doing that. Please read sections 0 and 1 of these lecture notes and check out the modern version of the example code here.
Applying this idiom to your code, we get the following.
class RoseTree {
var NodeType: int
var id: string
var children: array<RoseTree>
ghost var repr: set<object>
predicate Valid()
reads this, repr
decreases repr
{
&& this in repr
&& children in repr
&& (forall i | 0 <= i < children.Length ::
children[i] in repr
&& children[i].repr <= repr
&& this !in children[i].repr
&& children[i].Valid())
}
constructor(nt: int, id: string, children: array<RoseTree>)
requires forall i | 0 <= i < children.Length :: children[i].Valid()
ensures Valid()
{
this.NodeType := nt;
this.id := id;
this.children := children;
this.repr := {this, children} +
(set i | 0 <= i < children.Length :: children[i]) +
(set x, i | 0 <= i < children.Length && x in children[i].repr :: x);
}
}
function SetMax(s: set<int>): int
requires s != {}
ensures forall x | x in s :: SetMax(s) >= x
{
var x :| x in s;
if s == {x} then
x
else
var y := SetMax(s - {x});
assert forall z | z in s :: z == x || (z in (s - {x}) && y >= z);
if x > y then x else y
}
function height(node: RoseTree): nat
requires node.Valid()
reads node.repr
{
if node.children.Length == 0 then
1
else
var c := set i | 0 <= i < node.children.Length :: height(node.children[i]);
assert height(node.children[0]) in c;
assert c != {};
SetMax(c) + 1
}
do all instances of a class have the constructor ensure statements applied implicitly or only if explicitly constructed using the constructor?
I'm not sure if I understand this question. I think the answer is "no", though. Since a class might have multiple constructors with different postconditions.

Multiple conditions in a for loop?

I am trying to figure out what this pseudocode would be in Julia code:
Pseudocode:
for (i = 0; (i < 32) && (array[i] ≠ nil); i += 1) do
result := merge(array[i], result)
array[i] := nil
The multiple conditions seem to trip me up. I don't know how to format it in Julia. If anyone knows how I would appreciate it. I am new to the language.
There are multiple ways to do it in Julia. For example, you can use break statement
for i in 1:32 # in Julia we usually start numbering from 1
array[i] == nothing && break
result = merge(array[i], result)
array[i] = nothing
end
or while loop
i = 1
while i <= 32 && array[i] != nothing
result = merge(array[i], result)
array[i] = nothing
i += 1
end
You could do the looping and put the conditional inside:
nil = nothing #or any other sentinel value
for i in 1:32 #for i in eachindex(array)
if array[i] != nil #if cond1 & cond2 & cond3... &condn
result = merge(result, array[i])
array[i] = nil
end
end

FINDING total number of paths using backtracking

I'm trying to count total paths in a 20x20 grid(ProjectEuler #15) using backtracking.I've played around with it but the answer is always None. Any help would be appreciated(I know it can be solved using recursion or memoization but i want to solve it using backtracking)
def isvalid(maze,n,x,y):
if x<0 or y<0 or x>n or y>n :
return False
else: return True
def countPaths(maze,x,y,n,used,count):
if x==n-1 or y==n-1:
count+=1
return
if isvalid(maze,n,x,y):
used[x][y]=True
if (x+1<n and used[x+1][y]==False):
countPaths(maze,x+1,y,n,used,count)
if (x-1>0 and used[x-1][y]==False):
countPaths(maze,x-1,y,n,used,count)
if (y+1<n and used[x][y+1]==False):
countPaths(maze,x,y+1,n,used,count)
if (y-1>0 and used[x][y-1]==False):
countPaths(maze,x,y-1,n,used,count)
used[x][y]=False
return
Since in the base case, you are only returning 1 whenever end of row or column occurs it would yield wrong answer.
You should increment a counter signifying the number of times you are able to reach the final [n-1][n-1] i.e rightmost bottom cell.
bool isValid(int x, int y)
{
if (x < 0 || x >= n || y < 0 || y >= n)
return false;
return true;
}
void countPaths(int x, int y)
{
// cout << x << y << endl;
if (x == n - 1 && y == n - 1)
{
paths++;
return;
}
if (isValid(x, y))
{
visited[x][y] = true;
countPaths(x, y + 1);
countPaths(x + 1, y);
}
return;
}
Keeping paths & visited as global variables , I implemented the above approach.
For n=2 (1+1): 2
For n=3 (2+1): 6
For n=4 (3+1): 20
For n=5 (4+1): 70
however, this approach would not be viable for n=20.
I would suggest trying Dynamic Programming as it would simplify the process!

using ifelse in r with multiple returns

I was wondering how to set two or more results from a true ifelse statement.
For example, I would like to set y = 2 and t=3 if x=2. I was thinking the code would look something like this:
x=2
ifelse(x==2,y=2 & t=3, y=0 & t=0)
however this does not work.
You may use if-statement block:
if(x == 2){
y = 2
t = 3
}
else {
y = 0
t = 0
}
Alternatively, you can try:
ifelse(x == 2, {y = 2; t = 3;}, {y = 0; t = 0;})
As answered here: If statement with multiple actions in R, for the block IF statement, the ELSE should be on the same line as the previous curly bracket.
So, instead of
if(x ==2) {
y = 2
t = 3
}
else {
y = 0
t = 0
}
the format should be (the ELSE is on the same line as the previous curly bracket)
if(x ==2) {
y = 2
t = 3
} else {
y = 0
t = 0
}

SQL Get Rows With A Similar Column Value

I have a database that sometimes stores duplicate rows, however the duplicate is not clear cut, e.g. the following two column values would be a duplicate:
G12345 & G1234 --> because they are very similar
(a string comparison shows that the characters match 83.3%).
I need some help writing an SQL query that would retrieve values that are very similar to a string sent as part of the query, e.g. over 50% of characters matched.
Can someone help with this? I have a C# method as follows but not quite sure how to accomplish this in SQL:
static double StringCompare(string a, string b)
{
if (a == b) //Same string, no iteration needed.
return 100;
if ((a.Length == 0) || (b.Length == 0)) //One is empty, second is not
{
return 0;
}
var maxLen = a.Length > b.Length ? a.Length : b.Length;
var minLen = a.Length < b.Length ? a.Length : b.Length;
var sameCharAtIndex = 0;
for (var i = 0; i < minLen; i++) //Compare char by char
{
if (a[i] == b[i])
{
sameCharAtIndex++;
}
}
return sameCharAtIndex / maxLen * 100;
}
Thanks in advance.
Not sure if your trying to use SQL-Server or MySQL, but you could create and use the following function in SQL-Server:
create function StringCompare
(#A nvarchar(200),
#B nvarchar(200)
)
returns float
as
begin
if (
#A = #B
or (#A is null and #B is null)
)
begin
return 100.0
end
if (
((#A is null or len(#A) = 0) and (#B is not null and len(#B) > 0))
or ((#B is null or len(#B) = 0) and (#A is not null and len(#A) > 0))
)
begin
return 0.0
end
declare #maxLen int
set #maxLen = case when len(#A) > len(#B) then len(#A) else len(#B) end
declare #minLen int
set #minLen = case when len(#A) < len(#B) then len(#A) else len(#B) end
declare #sameCharAtIndex int
set #sameCharAtIndex = 0
declare #count int
set #count = 1
while (#count <= #minLen)
begin
if (SUBSTRING(#A, #count, 1) = substring(#B, #count, 1))
begin
set #sameCharAtIndex = #sameCharAtIndex + 1
end
set #count = #count + 1
end
return cast(#sameCharAtIndex as float) / cast(#maxLen as float) * 100.0
end
which could be used in any statement as follows:
select dbo.StringCompare('test', 'test'), dbo.StringCompare('nope', 'test'), dbo.StringCompare('partial', 'parsomethingelse')
please note, having a loop like this in sql running on many records can be inefficient. And you may want to consider whether you really have to do it in sql.
Use Mysql Like Operator instead of doing in service layer.
SELECT * FROM table WHERE column LIKE 'G12___' or 'G12%'.
SELECT * FROM table WHERE column LIKE '%input string as parameter%'.
The "_" wildcard in LIKE predicates means "one of any character," equivalent to "." in regular expressions.
See this for reference.

Resources