Clojure creating higher order first function - clojure

; Now create a function that takes a function (which produces a sequence)
; as an argument. Your function should invoke that function and return and
; return the first element from the returned sequence.
(is (higher-order-first-function? __))
Guys it is actually a part of my homework. I have 1000 lines of codes to do. This is just a part that i could not figure out how to do it. Can anyone help me how to solve this ? I tried every possible way but. I could not pass the testing.

So the steps are pretty clear from the comments:
Write a function that expects one parameter (use defn, fn, or #())
That parameter should be a function, so check for that (fn?)
Call that function
Return the first element in the returned sequence (first)

Related

How can i pass a list as argument for a function element by element in Elixir?

i have a function (lex_raw_tokens) that receives 2 arguments. Another function has 2 lists of elements that i need to pass as arguments to the other function, but element by element.
In the original code the function only received 1 argument and i called it using Enum.flat_map(sal, &lex_raw_tokens/1), sal being the list i'm passing. This worked but later on i had to change lex_raw_tokens to receive 2 arguments instead of 1.
I tried solving the issue with Enum.flat_map(sal, &lex_raw_tokens(&1, line)) and, while this technically works, line gets passed as an entire list instead of individual elements.
I'm still quite new to Elixir and i haven't found any other function to replace flat_map that does what i want and i haven't found a way to use flat_map like this.
I should also mention that the lists i'm passing have a variable lenght so i can't brute force my way around this problem. Also, both lists have the same lenght and have a relation, so I would need to use the first element of sal with the first element of line, the second with the second and so on.
Enum.zip/2 is your friend here.
sal = ~w|one two three|
line = ~w|apple orange lemon|
sal
|> Enum.zip(line)
|> Enum.flat_map(&lex_raw_tokens(elem(&1, 0), elem(&1, 1)))

Why is the return value of a function not evaluated but the return value of a macro is?

A function to add one and one:
(defn one-plus-one [] (list + 1 1))
when called returns:
(#object[clojure.core$_PLUS_ 0x47fa7bd5 "clojure.core$_PLUS_#47fa7bd5"] 1 1)
The same function body wrapped in a macro:
(defmacro one-plus-one [] (list + 1 1))
when called returns:
2
Why does Clojure expect macros to return expressions that can be evaluated?
Edit
The answers to the possible duplicate question tells how a macro is different from a function. But does not answer the why. Metaphorically, I know that an object left from an altitude drops vertically to hit the ground. My question is why does it drop vertically?
Let's just start with one thing many people know so well they forget to think about it explicitly when explaining macros, which causes others to be confused when learning to think about macros:
-----------> macros are functions <-------------
They are very often used to take lists of things that look like code, and are very often expected to return lists that can actually be run as code.
The difference between a macro and a function is not what it does (fundamentally), but when it does it. macros run while the code is "loading" and the value they return is run when the program runs.
when you write it as a macro it does two steps:
run the function to produce a list
run that returned list as code to produce a value
when you write it as a function it does one step:
run the function to produce a list
Then it stops.
The return value is diferent because the macro version takes that extra step of running the returned value as code.
code is data ... data is code ... yay lisp!

Lazy evaluation of expression in Elixir

I'm trying to figure out if there is a macro similar to delay in clojure to get a lazy expression/ variable that can be evaluated later.
The use case is a default value for Map.get/3, since the default value comes from a database call, I'd prefer it to be called only when it's needed.
Elixir's macro could be used for writing simple wrapper function for conditional evaluation. I've put one gist in the following, though it may be better/smarter way.
https://gist.github.com/parroty/98a68f2e8a735434bd60
"Generic" laziness is a bit of a tough nut to crack because it's a fairly broad question. Streams allow laziness for enumerables but I'm not sure what laziness for an expression would mean. For example what would a lazy form of x = 1 + 2 be? When would it be evaluated?
The thought that comes to mind for a lazy form of an expression is a procedure expression:
def x, do: 1 + 2
Because the value of x wouldn't be calculated until the expression is actually invoked (as far as I know). I'm sure others will correct me if I'm wrong on that point. But I don't think that's what you want.
Maybe you want to rephrase your question--leaving out streams and lazy evaluation of enumerated values.
One way to do this would be using processes. For example the map could be wrapped in a process like a GenServer or an Agent where the default value will be evaluated lazy.
The default value can be a function which makes the expensive call. If Map.get/3 isn't being used to return functions you can check if the value is a function and invoke it if it is returned. Like so:
def default_value()
expensive_db_call()
end
def get_something(dict, key) do
case Map.get(dict, key, default_value) do
value when is_fun(value) ->
value.() # invoke the default function and return the result of the call
value ->
value # key must have existed, return value
end
end
Of course if the map contains functions this type of solution probably won't work.
Also check Elixir's Stream module. While I don't know that it would help solve your particular problem it does allow for lazy evaluation. From the documentation:
Streams are composable, lazy enumerables. Any enumerable that generates items one by one during enumeration is called a stream. For example, Elixir’s Range is a stream:
More information is available in the Stream documentation.
Map.get_lazy and Keyword.get_lazy hold off on generating the default until needed, links the documentation below
https://hexdocs.pm/elixir/Map.html#get_lazy/3
https://hexdocs.pm/elixir/Keyword.html#get_lazy/3
You can wrap it in an anonymous function, then it will be evaluated when the function is called:
iex()> lazy = fn -> :os.list_env_vars() end
#Function<45.79398840/0 in :erl_eval.expr/5>
iex()> lazy.()

Different inputs for the same function

So I have a function that takes in 2 different inputs.
I've ran into the situation, however, where I very occasionally need a third input. Most of the time I don't though.
The solution I currently have is that the actual function I want to use is only called by 2 other functions. These two functions have the same name, but 1 takes 3 input and the other 2 (with this one just setting a null value to the third input before calling the original function).
This works quite well, but it feels like there might be a much better way of handling this type of problem. The only other solution I have is to declare a null value of the third input every time I go to call the first function, but that seems even messier.
Is there a better way to do this? Is it bad form the way I've written it?
Default arguments:
void foo (int x, int y, int z = 0);
Unless you pass a third value, z will be 0 by default inside the function.

Higher Order Functions in SML/NJ

I'm looking for help with a problem. I'm trying to write a function that passes both a list and function in ML. Basically what the program is supposed to do is take a list and run each element through the function. If the function returns true, then the element is added to a list and the list returned once the function has finished executing. Here's my code:
fun select(x:list, funct)= (* Define a new function that accepts a list and the prime function as a parameter*)
while (tl(x) not nil) do( (*While the tail is not empty*)
if funct(hd(x)) then (*Then run the function with the the head*)
val l = l::hd(x) (*Adds the head of x to the list *)
(*else 1+tl(x)*));
Any help would be very much appreciated.
A few pointers:
You pretty much never use loops in ML. Any time you need to iterate, write a recursive function.
You rarely need to specify types. In this case ML can infer, from the fact that you're calling tl(x), that x must be a list.
Instead of using hd(x) and tl(x) to decompose the list, you generally do this with pattern matching in the function arguments. Instead of a single argument x, write the argument as x::xs; x will be assigned to the head of the list, and xs to the tail.
Instead of using conditional statements to check the structure of your argument (in this case, whether your list is empty or not), you can write multiple function definitions with different patterns. ML will try them one by one until it finds one that fits.
The body of your function needs to be an expression which evaluates to your return value. Everything in ML is an expression; even if x then a else b is essentially a function which returns either a or b.
Keeping all this in mind, here's something to get you started:
fun select([], funct) = []
| select(x::xs, funct) = ...
The two cases here replace your while condition - the first will be evaluated only when your list is nil. The pattern in the second case automatically assigns values to the head and tail of your list. This definition is intended to be recursive; select([],funct)=[] is your base case, and select(x::xs,funct)=... should include a call to select(xs,funct).
take a list and run each element through the function. If the function returns true, then the element is added to a list and the list returned once the function has finished executing.
This is exactly the built-in List.filter function. No need to reinvent the wheel.