I'm trying to rewrite the cryptomath code from here and I'm getting this when I try to compile to JS;
Hint: used config file '/home/*******/.choosenim/toolchains/nim-1.6.8/config/nim.cfg' [Conf]
Hint: used config file '/home/*******/.choosenim/toolchains/nim-1.6.8/config/config.nims' [Conf]
...........................................................
/home/*******/nim/cryptomath.nim(6, 9) Error: expression 'a' is of type 'int' and has to be used (or discarded)
This is my code:
import std/random
import std/math
randomize()
proc gcd*(a: int, b: int): int =
while a != 0:
a, b = floorMod(b,a), a # fails here apparently
return (b+a)-a
proc find_mod_inverse*(a: int, m: int): int =
if gcd(a,m) != 1:
return -1
var
u1 = 1
u2 = 0
u3 = a
v1 = 0
v2 = 1
v3 = m
q = -1
while v3 != 0:
q = floorDiv(u3,v3)
v1 = (u1 - q * v1)
v2 = (u2 - q * v2)
v3 = (u3 - q * v3)
u1 = v1
u2 = v2
u3 = v3
return floorMod(u1,m)
I tried adding this, but it did nothing
discard a
before the end of the function
Your code has two issues:
Function arguments in Nim are immutable by default, so if you want to overwrite them locally, you need to shadow them or use var
Nim syntax for multiple variable assignment is different from Python and is done with tuple-like syntax
Fixed code would look like this:
import std/random
import std/math
randomize()
proc gcd*(a: int, b: int): int =
var (a, b) = (a, b)
while a != 0:
(a, b) = (floorMod(b,a), a)
return (b+a)-a
proc find_mod_inverse*(a: int, m: int): int =
if gcd(a,m) != 1:
return -1
var
u1 = 1
u2 = 0
u3 = a
v1 = 0
v2 = 1
v3 = m
q = -1
while v3 != 0:
q = floorDiv(u3,v3)
v1 = (u1 - q * v1)
v2 = (u2 - q * v2)
v3 = (u3 - q * v3)
u1 = v1
u2 = v2
u3 = v3
return floorMod(u1,m)
The compiler error is unclear, I agree.
Also, just a tip - keep in mind that standard Nim integers are limited by the architecture's native integer size, so if you want to operate on big numbers, you need to use a separate library.
I'm trying to get a toString or something similar of a lambda expression.
For example:
We have this expression
val isEvenThan1 = { x: Int ->
if (x % 2 == 0) 1
else 0
}
We wan a string output similar to this
"(x) -> { if (x % 2 == 0) 1 else 0 }"
I'm primarily looking for any libraries or work arounds to be able to output the internal logic of a function.
I'm trying to make the folowing function:
repcountIORIban :: IORef -> Int -> Int -> Int -> Int -> Lock -> IORef -> Lock -> Int -> Int -> IO ()
repcountIORIban count number lower modulus amountthreads lock done lock2 difference rest = do
if rest > number
then let extra = 1
else let extra = 0
if number + 1 < amountthreads
then
forkIO $ realcountIORIban(count lower (lower + difference + extra - 1) modulus lock done lock2)
repcountIORIban (count (number + 1) (lower + difference + extra) modulus amountthreads lock done lock2 difference rest)
else
forkIO $ realcountIORIban(count lower (lower + difference + extra - 1) modulus lock done lock2)
But I can't run the program from which this function is a part of. It gives me the error:
error: parse error on input `else'
|
113 | else let extra = 0
| ^^^^
I've got this error a lot of times withing my program but I don't know what I'm doing wrong.
This is incorrect, you can't let after then/else and expect those lets to define bindings which are visible below.
do if rest > number
then let extra = 1 -- wrong, needs a "do", or should be "let .. in .."
else let extra = 0
... -- In any case, extra is not visible here
Try this instead
do let extra = if rest > number
then 1
else 0
...
Further, you need then do if after that you need to perform two or more actions.
if number + 1 < amountthreads
then do
something
somethingElse
else -- use do here if you have two or more actions
...
this is my code:
sumDig i = if (i == 0) then 0 else ((mod i 10) + somaDig ((i-(mod i 10)/10)))
main = do
print (sumDig 4)
it's not working and I dont know why... it doesn't compile and the compiler message is not helping
the function is just to sum all characters of a given number, eg: 123 = 1 + 2 + 3 = 6, and it does that using n mod 10 + recursion from n/10
You've got a few errors.
The error about ambiguous types can be fixed by adding a type annotation to sumDig
sumDig :: Int -> Int
Another error is that somaDig is undefined. Did you mean to type sumDig?
If so, then the last compile error is the use of / on integers. You probably want div instead:
sumDig :: Int -> Int
sumDig i = if (i == 0) then 0 else ((mod i 10) + sumDig (((i-(mod i 10)) `div` 10)))
Does anyone know of a truly declarative language? The behavior I'm looking for is kind of what Excel does, where I can define variables and formulas, and have the formula's result change when the input changes (without having set the answer again myself)
The behavior I'm looking for is best shown with this pseudo code:
X = 10 // define and assign two variables
Y = 20;
Z = X + Y // declare a formula that uses these two variables
X = 50 // change one of the input variables
?Z // asking for Z should now give 70 (50 + 20)
I've tried this in a lot of languages like F#, python, matlab etc, but every time I tried this they come up with 30 instead of 70. Which is correct from an imperative point of view, but I'm looking for a more declarative behavior if you know what I mean.
And this is just a very simple calculation. When things get more difficult it should handle stuff like recursion and memoization automagically.
The code below would obviously work in C# but it's just so much code for the job, I'm looking for something a bit more to the point without all that 'technical noise'
class BlaBla{
public int X {get;set;} // this used to be even worse before 3.0
public int Y {get;set;}
public int Z {get{return X + Y;}}
}
static void main(){
BlaBla bla = new BlaBla();
bla.X = 10;
bla.Y = 20;
// can't define anything here
bla.X = 50; // bit pointless here but I'll do it anyway.
Console.Writeline(bla.Z);// 70, hurray!
}
This just seems like so much code, curly braces and semicolons that add nothing.
Is there a language/ application (apart from Excel) that does this? Maybe I'm no doing it right in the mentioned languages, or I've completely missed an app that does just this.
I prototyped a language/ application that does this (along with some other stuff) and am thinking of productizing it. I just can't believe it's not there yet. Don't want to waste my time.
Any Constraint Programming system will do that for you.
Examples of CP systems that have an associated language are ECLiPSe, SICSTUS Prolog / CP package, Comet, MiniZinc, ...
It looks like you just want to make Z store a function instead of a value. In C#:
var X = 10; // define and assign two variables
var Y = 20;
Func<int> Z = () => X + Y; // declare a formula that uses these two variables
Console.WriteLine(Z());
X = 50; // change one of the input variables
Console.WriteLine(Z());
So the equivalent of your ?-prefix syntax is a ()-suffix, but otherwise it's identical. A lambda is a "formula" in your terminology.
Behind the scenes, the C# compiler builds almost exactly what you presented in your C# conceptual example: it makes X into a field in a compiler-generated class, and allocates an instance of that class when the code block is entered. So congratulations, you have re-discovered lambdas! :)
In Mathematica, you can do this:
x = 10; (* # assign 30 to the variable x *)
y = 20; (* # assign 20 to the variable y *)
z := x + y; (* # assign the expression x+y to the variable z *)
Print[z];
(* # prints 30 *)
x = 50;
Print[z];
(* # prints 70 *)
The operator := (SetDelayed) is different from = (Set). The former binds an unevaluated expression to a variable, the latter binds an evaluated expression.
Wanting to have two definitions of X is inherently imperative. In a truly declarative language you have a single definition of a variable in a single scope. The behavior you want from Excel corresponds to editing the program.
Have you seen Resolver One? It's like Excel with a real programming language behind it.
Here is Daniel's example in Python, since I noticed you said you tried it in Python.
x = 10
y = 10
z = lambda: x + y
# Output: 20
print z()
x = 20
# Output: 30
print z()
Two things you can look at are the cells lisp library, and the Modelica dynamic modelling language, both of which have relation/equation capabilities.
There is a Lisp library with this sort of behaviour:
http://common-lisp.net/project/cells/
JavaFX will do that for you if you use bind instead of = for Z
react is an OCaml frp library. Contrary to naive emulations with closures it will recalculate values only when needed
Objective Caml version 3.11.2
# #use "topfind";;
# #require "react";;
# open React;;
# let (x,setx) = S.create 10;;
val x : int React.signal = <abstr>
val setx : int -> unit = <fun>
# let (y,sety) = S.create 20;;
val y : int React.signal = <abstr>
val sety : int -> unit = <fun>
# let z = S.Int.(+) x y;;
val z : int React.signal = <abstr>
# S.value z;;
- : int = 30
# setx 50;;
- : unit = ()
# S.value z;;
- : int = 70
You can do this in Tcl, somewhat. In tcl you can set a trace on a variable such that whenever it is accessed a procedure can be invoked. That procedure can recalculate the value on the fly.
Following is a working example that does more or less what you ask:
proc main {} {
set x 10
set y 20
define z {$x + $y}
puts "z (x=$x): $z"
set x 50
puts "z (x=$x): $z"
}
proc define {name formula} {
global cache
set cache($name) $formula
uplevel trace add variable $name read compute
}
proc compute {name _ op} {
global cache
upvar $name var
if {[info exists cache($name)]} {
set expr $cache($name)
} else {
set expr $var
}
set var [uplevel expr $expr]
}
main
Groovy and the magic of closures.
def (x, y) = [ 10, 20 ]
def z = { x + y }
assert 30 == z()
x = 50
assert 70 == z()
def f = { n -> n + 1 } // define another closure
def g = { x + f(x) } // ref that closure in another
assert 101 == g() // x=50, x + (x + 1)
f = { n -> n + 5 } // redefine f()
assert 105 == g() // x=50, x + (x + 5)
It's possible to add automagic memoization to functions too but it's a lot more complex than just one or two lines. http://blog.dinkla.net/?p=10
In F#, a little verbosily:
let x = ref 10
let y = ref 20
let z () = !x + !y
z();;
y <- 40
z();;
You can mimic it in Ruby:
x = 10
y = 20
z = lambda { x + y }
z.call # => 30
z = 50
z.call # => 70
Not quite the same as what you want, but pretty close.
not sure how well metapost (1) would work for your application, but it is declarative.
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
x = 10
y = 20
z = function() return x + y; end
x = 50
= z()
70
It's not what you're looking for, but Hardware Description Languages are, by definition, "declarative".
This F# code should do the trick. You can use lazy evaluation (System.Lazy object) to ensure your expression will be evaluated when actually needed, not sooner.
let mutable x = 10;
let y = 20;
let z = lazy (x + y);
x <- 30;
printf "%d" z.Value