Function to Lambda conversion - function

Im trying to convert this function into a lambda function but I am unsure of how to utilize the rotate in lambda. Any help is appreciated.Function is below.
list = [1, 2, 5, 9, 11, 43, 16, 2]
def rotate(l, n):
return l[-n:] + l[:-n]
rotate(list, 3)

well this is a bit tautalogicial, but you can invoke the function in the lambda with the same parameters, something like this:
lambda l, n: rotate(l, n)
and even give it a name:
my_rotate = lambda l, n: rotate(l, n)
But after all that, you're just wrapping rotate in an identical function, so you're better off using rotate on it's own. As a preference, lambdas should be used for extremely simple functions in the next few lines

Related

How does the first parameter affect the result of array.map( ) method?

I'm running this snippet in JS Bin:
let array1 = [1, 4, 9, 16]
let array2=[1, 4, 9, 16]
const map1=array2.map(x=>x*2)
console.log(map1)
//Output is:[2, 8, 18, 32]
const map2 = array2.map((y,x) => x * 2)
console.log(map2)
//Output is: [0, 2, 4, 6]
How is the first parameter affecting the output of map function?
Edit: Two precise answers. Just giving some context on why I asked this question. Thanks to SO, now I know that first parameter is value at the index, while second is the index of the array. I had seen this being used in an example: map((_,x)=>itemName+=x). If I pass only one parameter, it'd turn it into itemName+valueAtTheIndex, however if I pass two arguments and use the second, it will turn into itemName1,itemName2,.....
Quite handy!
_ is not affecting the output of .map. It's the argument you are using to do the calculation that's affecting the output.
.map(entry, index) is the syntax when you use two args in a map function.
let arr = [1, 4, 9, 16]
const ret = arr.map(x => x * 2)
console.log(ret)
// Output is: [2, 8, 18, 32]
// here, x is array index - 0, 1, 2, 3
const ret = arr.map((_, x) => x * 2)
console.log(ret)
// Output is: [0, 2, 4, 6]
// try it with `_`
// You'll get the desired output
const ret = arr.map((_, x) => _ * 2)
console.log(ret)
// Output is: [2, 8, 18, 32]
In your two snippets you call "x" two different things. In the first one x is the first argument of the function array.map(), which will contain each value, while in the second snippet x is the second argument and it will contain each array index.
In the first case x will contain the array values (which is what you expected) while in the second case x will contain the values 0,1,2,3, which yield the result you got.
The identifier _ has no special meaning but it is a valid argument identifier. you could have called it y and would have gotten the same result.
first argument in map function is the current value in your array while second column is index.
_ is used for ignoring the first column.

Writing an exception function

I am currently learning on an online learning platform, and my code has to pass the test cases(included below)
Heres the question:
Write a higher-order function exception_function which will return a function with exceptions. exception_function should take in a function f(x), an integer input, and an integer output, and return another function g(x). The output of g(x) should be the same as f(x), except that when x is the same as the integer input, the output will be returned.
For example, given that we have a function sqrt which returns the square root of the argument. Using new_sqrt = exception_function(sqrt, 7, 2) we obtain new_sqrt, which behaves similarly to sqrt except for new_sqrt(7), where the value of 2 will be returned.
Below is the answer template
from math import *
def exception_function(f, rejected_input, new_output):
"""Your code here"""
pass
#################
#DO NOT REMOVE#
#################
new_sqrt = exception_function(sqrt, 7, 2)
Test Cases:
new_sqrt(9) -expected answer 3
new_sqrt(7) -expected answer 2
Here is what im not sure about.
How to control what f will return without changing f itself?
Thank you very much for your time.
Managed to solve it!
def exception_function(f, rejected_input, new_output):
def inner_function(x):
if x==rejected_input:
return new_output
else:
return f(x)
return inner_function
new_sqrt = exception_function(sqrt, 7, 2)

defining parameters of multiple types in Nim

Say I have a two classes and a procedure that modifies either class in the same manner. How do I specify that a parameter can be either class (instead of rewriting or overloading the function for each class)? A simple example:
type
Class1[T] = object
x: T
Class2[T] = object
x: T
y: T
# this works fine
proc echoX[T](c: Class1[T]|Class2[T]) =
echo c.x
# this does not work
proc addToX[T](c: var Class1[T]|Class2[T], val: T) =
c.x += val
var c1: Class1[int]
var c2: Class2[int]
# this works fine
echoX(c1)
echoX(c2)
# this does not work
addToX(c1, 10)
addToX(c2, 100)
I get the following error.
Error: for a 'var' type a variable needs to be passed
If I use a separate procedure for each class, things work fine.
proc addToX[T](c: var Class1[T], val: T) =
c.x += val
proc addToX[T](c: var Class2[T], val: T) =
c.x += val
This is just a simple example where it's easy to rewrite the function. But I'm looking to do this for more complex classes and procedures. In some cases inheritance might be appropriate, but it doesn't seem like Nim classes can be passed as variables to procedures in place of the base class.
A bracket fixes this problem, otherwise the var just applies to Class1[T]:
proc addToX[T](c: var (Class1[T]|Class2[T]), val: T) =
You may run into another compiler bug with this later: https://github.com/nim-lang/Nim/issues/1385
Maybe in your use case object variantes or inheritance and methods will work better.

Scala: Passing Vs applying function

Let's say we have the following code snippet:
List(1, 2, 3)
.map(doubleIt) // passing function
.map(x => doubleIt(x)) // applying function
def doubleIt(i: Int): Int = 2 * i
As you can see we can either pass doubleIt as a function literal or apply it inside another anonymous Lambda. I have always wondered which approach is better. I personally prefer passing a function literal as it seems like second approach would end up creating an extra wrapper Lambda for no good reason, but I am not 100% positive my reasoning is correct.
I am curious to know what the pro/cons of each style are and whether one is definitely better than the other.
This might change in Scala 2.12+, but at the moment both approaches are identical. As a test, I created the following:
class Test {
def testPassingFunction: List[Int] = List(1, 2, 3).map(doubleIt)
def testApplyingFunction: List[Int] = List(1, 2, 3).map(x => doubleIt(x))
def doubleIt(i: Int): Int = 2 * i
}
I then compiled it and used javap to disassemble the bytecode. Both functions are identical (except for different Strings. In all cases a new class that extends from Function1 is created that calls the appropriate method. As #Mike says in the comments, the Scala compiler converts everything to the second form.
It turns out that it depends somewhat on what your "function" is. If it is actually a function (that is, a function value, defined as val doubleIt = (x: Int) => 2 * x), then your hunch is correct. The version in which you pass a function literal that simply applies doubleIt (i.e., l map { x => doubleIt(x) } is compiled just as written, resulting in an anonymous function that delegates to doubleIt. Passing doubleIt as a function value takes out the middle man. If doubleIt is a method, on the other hand, then both forms are compiled identically.
You can easily verify this yourself at the REPL. Define the following class:
class A {
val l = List(1,2,3)
val f = (x: Int) => 2 * x
def g(x: Int) = 2 * x
def m1 = l map f
def m2 = l map { x => f(x) }
def m3 = l map g
def m4 = l map { x => g(x) }
}
Then run :power and :javap -v A.
That said, the distinction is unlikely to make a practical difference in any but the most performance-critical code. In ordinary circumstances, code clarity is the more important consideration and depends somewhat on who will be reading your code in the future. Personally, I tend to prefer the concise lst map doubleIt form; this form eliminates a bunch of syntactic noise that adds nothing semantically. I suppose the longer form may be considered more explicit, especially for developers that aren't very familiar with the map method. The literal reading matches the intent quite well: "(Given) list, map (each) x to doubleIt(x)". Your team will have to decide what's best for you and your organization.

Passing multiple parameters

I'm trying to convert an existing C function to Erlang but am having a bit of trouble understanding how it's going to work. Let's say I have the following function in C:
void(int *x,int *y,int z,int a)
{
if(z<a)
{
*x = z + a;
*y = z - a;
}
}
How would I write something like that in Erlang as a function module? I understand that normally you write your function and it would return an operation. But what if I have to do calculations on multiple variables?
you may return a tuple like: {X, Y}
Here is a function that doubles two values given as input:
-module(my_module).
-export([doubleus/2]).
doubleus(X, Y) ->
{X*2, Y*2}.
In the shell:
1> c(my_module).
{ok, my_module}
2> {A, B} = my_module:doubleus(3,4).
{6, 8}
Operating with pointers - means that you may change state of some location in memory (for sequential flow it is not so bad).
But in concurrency environment this may indirectly cause unpredictable changes in every process, that pointed on that location (especially in race condition).
That's why there are so many concurrency oriented mechanisms in Java.
But this is not Erlang way. In general - there is no pointers, and no shared memory in Erlang.
You may store state, for example, in tuple { X, Y, Z, A }, and pass it from function to function. Sometimes your functions will return new state tuple.
In the context of the above, your function may look like:
-module( my_module ).
-export( [ f/1 ] ).
f( { _X, _Y, Z, A } ) when Z < A -> { Z + A, Z - A, Z, A };
%% othervise - don't change the state
f( State ) -> State.