What is the correct function definition syntax in CoffeeScript? - syntax

On the official CoffeeScript website the syntax for defining a function is
square = (x) -> x * x
However, on some other websites I found out that the syntax could also be
square: (x) -> x * x
Is one of the options preferred?

There is a huge difference between those two options. Firstly, they have nothing to do with function syntax, which is always (x) -> x * x. They only differs in what you are doing with the function.
The first option defines a local variable square and assign that function to it. hence afterwards you can simply call square(2) to get 4.
Second option is creating a javascript object. If this is the last line of some function, this is its return value. Object has to be assigned to some variable, otherwise it is lost:
functions =
square: (x) -> x * x
functions.square(2)

Related

How can I emulate the results of this if then then statement while using correct syntax?

Working on an exercise for university class and cant seem to represent what I am trying to do with correct syntax in ocaml. I want the function sum_positive to sum all the positive integers in the list into a single int value and return that value.
let int x = 0 in
let rec sum_positive (ls: int list) = function
|h::[] -> x (*sum of positive ints in list*)
|[] -> 0
|h::t -> if (h >= 0) then x + h then sum_positive t else sum_positive t (*trying to ensure that sum_positive t will still run after the addition of x + h*)
On compiling I am met with this error,
File "functions.ml", line 26, characters 34-38:
Error: Syntax error
This points to the then then statement I have in there, I know it cannot work but I cant think of any other representations that would.
You have if ... then ... then which is not syntactically valid.
It seems what you're asking is how to write what you have in mind in a way that is syntactically valid. But it's not clear what you have in mind.
You can evaluate two expressions in OCaml sequentially (one after the other) by separating them with ;. Possibly that is what you have in mind.
However it seems to me your code has bigger problems than just syntax. It appears you're trying to use x as an accumulated sum for the calculation. You should be aware that OCaml variables like x are immutable. Once you say let x = 0, the value can't be changed later. x will always be 0. The expression x + h doesn't change the value of x. It just evaluates to a new value.
The usual way to make this work is to pass x as a function parameter.
I was getting an issue that had involved the parameter of , I believe it was because I was trying to add an int value to function of type int list. This is what I ended up with.
let rec sum_positive = function
|[] -> 0
|h::t -> if h > 0 then h + (sum_positive t) else sum_positive t
a lot simpler than I thought it out to be.

Return an integer literal from a Scheme function

I've been reading about Scheme functions and have not seen one that simply returns an integer literal; likely because it would not be a very useful function. However, I am interested in trying to write a simple function in Scheme that takes arguments and just returns an integer. My function is:
(define (f x y) 1)
When I call the function with:
(f 4 5)
The result is:
4
5
Why would the function return both of the arguments rather than simply returning 1?

Retrieve method content as an `Expr`ession

I have a function f defined as follows.
f(x, y) = 3x^2 + x*y - 2y + 1
How can I retrieve the following quote block for this method, which includes the function contents?
quote # REPL[0], line 2:
((3 * x ^ 2 + x * y) - 2y) + 1
end
As folks have mentioned in the comments, digging through the fields of the methods like this isn't a stable or officially supported API. Further, your simple example is deceiving. This isn't, in general, representative of the original code you wrote for the method. It's a simplified intermediate AST representation with single-assignment variables and drastically simplified control flow. In general, the AST it returns isn't valid top-level Julia code. It just so happens that for your simple example, it is.
That said, there is a documented way to do this. You can use code_lowered() to get access to this intermediate representation without digging through undocumented fields. This will work across Julia versions, but I don't think there are official guarantees on the stability of the intermediate representation yet. Here's a slightly more complicated example:
julia> f(X) = for elt in X; println(elt); end
f (generic function with 1 method)
julia> code_lowered(f)[1]
LambdaInfo template for f(X) at REPL[17]:1
:(begin
nothing
SSAValue(0) = X
#temp# = (Base.start)(SSAValue(0))
4:
unless !((Base.done)(SSAValue(0),#temp#)) goto 13
SSAValue(1) = (Base.next)(SSAValue(0),#temp#)
elt = (Core.getfield)(SSAValue(1),1)
#temp# = (Core.getfield)(SSAValue(1),2) # line 1:
(Main.println)(elt)
11:
goto 4
13:
return
end)
julia> code_lowered(f)[1] == methods(f).ms[1].lambda_template
true
If you really want to see the code exactly as it was written, the best way is to use the embedded file and line information and refer to the original source. Note that this is precisely the manner in which Gallium.jl (Julia's debugger) finds the source to display as it steps through functions. It's undocumented, but you can even access the REPL history for functions defined interactively. See how Gallium does it through here.
First, retrieve the method using methods(f).
julia> methods(f)
# 1 method for generic function "f":
f(x, y) at REPL[1]:1
julia> methods(f).ms
1-element Array{Method,1}:
f(x, y) at REPL[1]:1
julia> method = methods(f).ms[1]
f(x, y) at REPL[1]:1
From here, retrieving the Expression is straightforward; simply use the lambda_template attribute of the method.
julia> method.lambda_template
LambdaInfo template for f(x, y) at REPL[1]:1
:(begin
nothing
return ((3 * x ^ 2 + x * y) - 2 * y) + 1
end)
Edit: This does not work in Julia v0.6+!

Scheme procedure with 2 arguments

Learned to code C, long ago; wanted to try something new and different with Scheme. I am trying to make a procedure that accepts two arguments and returns the greater of the two, e.g.
(define (larger x y)
(if (> x y)
x
(y)))
(larger 1 2)
or,
(define larger
(lambda (x y)
(if (> x y)
x (y))))
(larger 1 2)
I believe both of these are equivalent i.e. if x > y, return x; else, return y.
When I try either of these, I get errors e.g. 2 is not a function or error: cannot call: 2
I've spent a few hours reading over SICP and TSPL, but nothing is jumping out (perhaps I need to use a "list" and reference the two elements via car and cdr?)
Any help appreciated. If I am mis-posting, missed a previous answer to the same question, or am otherwise inappropriate, my apologies.
The reason is that, differently from C and many other languages, in Scheme and all Lisp languages parentheses are an important part of the syntax.
For instance they are used for function call: (f a b c) means apply (call) function f to arguments a, b, and c, while (f) means apply (call) function f (without arguments).
So in your code (y) means apply the number 2 (the current value of y), but 2 is not a function, but a number (as in the error message).
Simply change the code to:
(define (larger x y)
(if (> x y)
x
y))
(larger 1 2)

Differentiate an infix formal language functions

I have a source file like (without loss of generality (only to image a possible syntax)):
function a()
return g // global variable without any internal structure exactly
end
function b(x, y)
local z = x * y
return z + 1
end
function c(z, t)
return b(z * z, a())
end
// ...etc
I want to defferentiate any function WRT to some variable.
All the formal parametres we can treat as a functions with unknown at derive time internal structure.
If I stand correct further, then the following is truth (for depending symbols ' is part of symbol, for global variables is operator during substitute time stage (def: g{g} is one, but g{y} is zero)):
function a'()
return g';
end
function b'(x, y, x', y')
local z' = x' * y + x * y'
return z' + 0
end
But what to do with last function? Namely, with actual parameters in substitution of function b?
Is there any ready to use implementations of general algorithm to work with the above? What to do with higher order derivatives (especially interesting, how to handle the formal parameters)? Are there any other possible unclear cases?
I would suggest having your parameters be symbolic expressions that know how to respond to derivatives, and having all operations take functions and return functions. Then you will get a final expression that knows how to be represented as a derivative. Furthermore you can do things like partial derivatives at a later point because you have the symbolic expression.
For a real example of what I mean, see http://www.elem.com/~btilly/kelly-criterion/js/advanced-math.js for a library that I wrote to solve a calculus problem in JavaScript, and search for "Optimize if requested" in the source for http://www.elem.com/~btilly/kelly-criterion/betting-returns2.html to see how I used it. See http://www.elem.com/~btilly/kelly-criterion/ for an explanation of why I was writing that code.
In that example I, of course, was not working from infix notation. But that is a standard parsing problem that I think you know how to solve.

Resources