What is an elegant way to abstract functions - not objects? - functional-programming

I have a function that logs into a sensor via telnet/pexpect and acts as a data collector.
I don't want to rewrite the part that logs in, grabs the data, and parses out relevant output from it (pexpect). However, I need to do different things with this code and the data it gathers
For example, I may need to:
Time until the first reading is returned
Take the average of a varying number of sensor readings
Return the status (which is one piece of data) or return the sensor
reading (which is a separate piece of
data) from the output
Ultimately, it should still login and parse output the same and I want to use one code block for that part.
Higher up in the code, it's being used instantaneously. When I call it, I know what type of data I need to gather and that's that. Constructing objects is too clumsy.
My usage has outstripped adding more arguments to a single function.
Any ideas?

This is such a common situation, I'm surprised you haven't already done what everyone else does.
Refactor your function to decompose it into smaller functions.
Functions are objects, and can be passed as arguments to other functions.
def step1():
whatever
def step2():
whatever
def step2_alternative():
whatever
def original( args ):
step1()
step2()
def revised( args, step2_choice ):
step1()
step2_choice()
Now you can do this.
revised( step2 )
revised( step2_alternative )
It's just OO programming with function objects.

Could you pass a data processing function to the function you described as an argument?
That may be more or less elegant, depending on your taste.
(Forgive me: I know nothing about pexpect, and I may even have misunderstood your question!)

Related

Julia type conversion best practices

I have a function which requires a DateTime argument. A possibility is that a user might provide a ZonedDateTime argument. As far as I can tell there are three possible ways to catch this without breaking:
Accept both arguments in a single method, and perform a type conversion if necessary via an if... statement
function ofdatetime(dt::AbstractDateTime)
if dt::ZonedDateTime
dt = DateTime(dt, UTC)
end
...
end
Define a second method which simply converts the type and calls the first method
function ofdatetime(dt::DateTime)
...
end
function ofdatetime(dt::ZonedDateTime)
dt = DateTime(dt, UTC)
return ofdatetime(dt)
end
Redefine the entire function body for the second method
function ofdatetime(dt::DateTime)
...
end
function ofdatetime(dt::ZonedDateTime)
dt = DateTime(dt, UTC)
...
end
Of course, this doesn't apply when a different argument type implies that the function actually do something different - the whole point of multiple dispatch - but this is a toy example. I'm wondering what is best practice in these cases? It needn't be exclusively to do with time zones, this is just the example I'm working with. Perhaps a relevant question is 'how does Julia do multiple dispatch under the hood?' i.e. are arguments dispatched to relevant methods by something like an if... else/switch... case block, or is it more clever than that?
The answer in the comments is correct that, ideally, you would write your ofdatetime function such that all operations on dt within your function body are general to any AbstractDateTime; in any case where the the difference between DateTime and ZonedDateTime would matter, you can use dispatch at that point within your function to take care of the details.
Failing that, either of 2 or 3 is generally preferable to 1 in your question, since for either of those, the branch can be elided in the case that the type of df is known at compile-time. Of the latter two, 2 is probably preferable to 3 as written in your example in terms of general code style ("DRY"), but if you were able to avoid the type conversion by writing entirely different function bodies, then 3 could actually have better performance than if the type conversion is at all expensive.
In general though, the best of all worlds is to keep most your code generic to either type, and only dispatch at the last possible moment.

Backtracking implementation in c (without using any data structure)

after many hours of trying i decided to post my problem here.
i want to solve this question with "Backtracking" implementation without any data-structure.
write a recursive function that recieve integer number (>=0) and will print all options that the number can to be broke down, but the numbers can be only odd numbers.
and we have a global const variable N and his purpose is to tell us how many odd numbers this number can split up(Max splits).
For example:
function that receive number=7 and we have a global variable the we defined up to our code N=6
the function will print:
7=1+1+1+1+3, 7=1+3+3, 7=1+1+5, 7=7
note that: 1+3+3 and 3+1+3 is the same solution and the function will not print that option twice, only once time.
Thanks a lot !

Using argument of outer function as global variable for a function defined inside outer function - "function factory"

Is this bad practice? It seems like a lot could go wrong here.*
I am setting the argument of an outer function to be a global variable for a function defined inside it. I am just doing this to work around some existing code.
f = function(a,b){h = function(c){print(b);b+c}}
myh = f(1,2)
myh(7)
#[1] 2
#[1] 9
*On the other hand, it's perfectly acceptable to write something like
h = function(c){print(7);7+c}
Creating a function that creates functions (or a function factory) is a totally acceptable code practice. See https://adv-r.hadley.nz/function-factories.html for more details on certain parts of the technical implementation in R.
It is most often used if you need to create functions at runtime or you need to create a lot of similar funcions.
The function factory you have created could be considered similar to a function factory that would create different sized counters that told the user how much the amount was incremented by.
It is important to keep track of the functions you create this way however.
Let me know if you'd like more clarification on anything.
(One possible bad practise in the function you have created though is an unused argument a).

How to mock current time in elixir

I have some tests which depends on current time and am not able to find a solution for it so far. I have tried some mocking libraries like mock but it mocks the whole module and it fails.
Any help will be really appreciated(if I only mock DateTime.utc_now everything is ok)
Note: tests depends heavily on other DateTime and Date functions so mocking whole modules is not a very good option(I have tried this also but failed due to very complex cases and I need this in many tests)
Actual test:
I have two dates, start date and end date as input to a function which I am trying to test. Before calling the function for test purpose I insert some data relevent to the current week(current dat to next seven days). Now the function will get current datetime and check for specific days(each record will tell if it applies to current day of the week and for current time period range on which being iterated -> start and end dates).
e.g one record applies for mon -> 2:12 to 3:13
The solution which best suits my needs(simple, works well and according to the requirements described above) is:
define your own function/service MyDateTime.utc_now/0 and mock it in your tests. — Reference.
NB this answer is obsoleted since Elixir v1.8 Now the default parameters are not evaluated at compile time. Credits #HentikN.
Now the function will get current datetime and check for specific days [...]
This is where the real issue sits. You made your function not pure for no reason. Usually the purity means the function has no side effects, but blindly changing the outcome depending on the outside world does not sound as a robust approach either.
That said, you should make this function to accept a parameter now or like (it might be defaulted to now for the sake of brevity):
- def my_func(param) do
+ def my_func(param, dt \\ nil) do
+ dt = if is_nil(dt), do: DateTime.utc_now(), else: dt
(Naïve dt \\ DateTime.utc_now() won’t work because function heads are evaluated at the compile time.)
Now in your tests you might call this function passing the time you want and (which is even more important) your function is not a blackbox depending on the unrelated conditions from the outside anymore.

Best practice to access variables several function layers deep

I am often confronted with the following situation when I debug my Julia code:
I suspect that a certain variable (often a large matrix) deep inside my code is not what I intended it to be and I want to have a closer look at it. Ideally, I want to have access to it in the REPL so I can play around with it.
What is the best practice to get access to variables several function layers deep without passing them up the chain, i.e. changing the function returns?
Example:
function multiply(u)
v = 2*u
w = subtract(v)
return w
end
function subtract(x)
i = x-5
t = 10
return i-3t
end
multiply(10)
If I run multiply() and suspect that the intermediate variable i is not what I assume it should be, how would I gain access to it in the REPL?
I know that I could just write a test function and test that i has the intended properties right inside subtract(), but sometimes it would just be quicker to use the REPL.
This is the same in any programming language. You can use debugging tools like ASTInterpreter2 (which has good Juno integration) to step through your code and have an interactive REPL in the current environment, or you can use println debugging where you run the code with #show commands in there to print out values.

Resources