G'day guys,
Trying currently to finish up a bit of homework I'm working on, and having an issue where I'm trying to apply map across a function that accepts multiple inputs.
so in the case I'm using processList f (x:xs) = map accelerateList f xs x xs
processList is given a floating value (f) and a List that it sorts into another List
Accelerate List takes a floating value (f) a List and a List Object through which it returns another List Object
I know my Accelerate List code is correct, but I cannot for the life of me get the syntax for this code working:
processList :: Float -> [Object] -> [Object]
accelerate f [] = []
accelerate f [x] = [(accelerateForce f x x)]
accelerate f (x:xs) = map accelerateList f xs x xs
Any ideas? I've been scratching my head for about 3 hours now. I know it's something really simple.
First of you will probably want to use some parenthesis here:
map accelerateList f xs x xs
The function map takes exactly two arguments (not five), so you should do something like this for example:
map (accelerateList f xs x) xs
But on the other hand, that doesn't fit with your function signatures. The problem is probably that you haven't structured your solution in a good enough way. Might be a separate question, but explaining what you're trying to accomplish with the accelerate-function (or which ever one is the "top" one) would certainly help.
Related
I cant wrap my brain around tail recursion specifically in ocaml also explain why one calls the "in" function at the end. P.S. I am talking most basic tail recursive function.
Functions communicate via one of three methods.
Their argument(s). This is the input data.
Their return value. This is the output.
They can modify some mutable state outside of the function's scope. Don't do this if you can possibly avoid it.
Everytime a function is called, a stack frame is created with the data the function needs to do its job. When it's done its return value is returned "up" the stack to its caller.
Consider a simple sum function which sums up a list.
let rec sum lst =
match lst with
| [] -> 0
| x::xs -> x + sum xs
Pretty simple. The sum of an empty list of course is 0. The sum of a non-empty list is the first element plus the sum of the rest of the list.
When we recursively call sum xs that call doesn't know what x is. It can't perform that addition. It can only sum the remaining list and then send that back up the stack for the addition to happen.
If we do this with a small list, it's not really an issue. The stack is limited, but not limited enough for that to be a concern.
But if we tried it with a list with a much larger number of elements, we'll run out of stack space and get an error.
The tail-recursive version of the sum function needs to make sure that its last call can provide a complete answer with no need to return info back up the stack. That means when the function is called, the caller needs to pass any required information to the called via its argument(s).
To accomplish this, we use an accumulator, which is commonly called acc.
let rec tail_sum acc lst =
match lst with
| [] -> acc
| x::xs -> tail_sum (acc + x) xs
As tail_sum iterates over the list, it keeps a running accumulation of the sum. When the list is empty, it returns that accumulator. We just need to always call tail_sum with a starting accumulator of 0.
tail_sum 0 [1; 2; 3; 4; 5; 6]
This is ugly, so you'll commonly see this hidden by using a locally nested helper function.
let tail_sum lst =
let rec helper acc lst =
match lst with
| [] -> acc
| x::xs -> helper (acc + x) xs
in
helper 0 lst
Imagine I work in an office. My boss asks me to find out when his lunch is going to be ready.
Scenario 1: I ask my secretary to tell me when lunch will be ready. He asks the cafe manager to tell him when lunch will be ready. The cafe manager asks the chef to tell her when lunch will be ready. They all report back to each other, and eventually to me, and I tell the boss when lunch will be ready.
Scenario 2: I ask my secretary to tell the boss when lunch will be ready. My secretary tells the cafe manager to tell the boss when lunch is ready. The cafe manager tells the chef to tell the boss when lunch is ready. The chef directly contacts the boss with the requested information.
The more direct approach in scenario 2 is possible because the information about the end recipient is passed along at each stage. The same goal is achieved, but this time once it has exited each person's hands, they can forget about it. They are no longer necessary to achieving the goal.
A tail call is the last expression in a function, which becomes the result of the whole function, e.g.,
let foo x = x + 1
let bar x =
let x = x + 1 in
foo x (* here foo is in the tail position *)
When a call is in the tail position, it could be made very cheaply, without allocating any administrative data on the program stack, which is usually necessary for more general calls, e.g.,
let baz x =
1 + foo x (* foo is not in the tail position! *)
In this example, we see that <...> + <...> is the last expression, so the computer needs to evaluate both sides of + and store them in some place in the memory before it can finally sum them up. This "some place in the memory" is usually the stack, which is a scarce resource on most modern operating systems. The scarcity of the stack becomes especially important if we make such calls iteratively.
Finally, if a tail call is recursive, it is called a tail-recursive call. Tail-recursive calls are very efficient in the implementation of iterative procedures, where instead of relying on specialized ad-hoc control-flow structures, like for and while, we can express the repetitiveness of the process in a more legible way, e.g.,
let rec contains_element k = function
| [] -> false
| x :: _ when k = x -> true
| _ :: xs -> contains_element k xs
describes naturally that a list contains an element k if either its head is k or if the tail of the list contains the element k. This algorithm is also a good showcase for an exception to the above-specified rule that a tail calls must be the last call in the function,
(* this version is also tail recursive! *)
let rec contains_element k = function
| [] -> false
| x :: xs -> x = k || contains_elements xs
It is because OCaml treats a call on the right-hand side of a short-circuit operator1 as a tail call, since you don't need to compute both operands before applying the operator.
1) which are || and && in OCaml that stand for logical disjunction (OR) and conjunction (AND).
I found this problem in the website 99 problems in ocaml. After some thinking I solved it by breaking the problem into a few smaller subproblems. Here is my code:
let rec frequency x l=
match l with
|[]-> 0
|h::t-> if x=[h] then 1+(frequency x t)
else frequency x t
;;
let rec expand x n=
match n with
|0->[]
|1-> x
|_-> (expand x (n-1)) # x
;;
let rec deduct a b=
match b with
|[]-> []
|h::t -> if a=[h] then (deduct a t)
else [h]# (deduct a t)
;;
let rec pack l=
match l with
|[]-> []
|h::t -> [(expand [h] (frequency [h] l))]# (pack (deduct [h] t))
;;
It is rather clear that this implementation is overkill, as I have to count the frequency of every element in the list, expand this and remove the identical elements from the list, then repeat the procedure. The algorithm complexity is about O(N*(N+N+N))=O(N^2) and would not work with large lists, even though it achieved the required purpose. I tried to read the official solution on the website, which says:
# let pack list =
let rec aux current acc = function
| [] -> [] (* Can only be reached if original list is empty *)
| [x] -> (x :: current) :: acc
| a :: (b :: _ as t) ->
if a = b then aux (a :: current) acc t
else aux [] ((a :: current) :: acc) t in
List.rev (aux [] [] list);;
val pack : 'a list -> 'a list list = <fun>
the code should be better as it is more concise and does the same thing. But I am confused with the use of "aux current acc" in the inside. It seems to me that the author has created a new function inside of the "pack" function and after some elaborate procedure was able to get the desired result using List.rev which reverses the list. What I do not understand is:
1) What is the point of using this, which makes the code very hard to read on first sight?
2) What is the benefit of using an accumulator and an auxiliary function inside of another function which takes 3 inputs? Did the author implicitly used tail recursion or something?
3) Is there anyway to modify the program so that it can pack all duplicates like my program?
These are questions mostly of opinion rather than fact.
1) Your code is far harder to understand, in my opinion.
2a) It's very common to use auxiliary functions in OCaml and other functional languages. You should think of it more like nested curly braces in a C-like language rather than as something strange.
2b) Yes, the code is using tail recursion, which yours doesn't. You might try giving your code a list of (say) 200,000 distinct elements. Then try the same with the official solution. You might try determining the longest list of distinct values your code can handle, then try timing the two different implementations for that length.
2c) In order to write a tail-recursive function, it's sometimes necessary to reverse the result at the end. This just adds a linear cost, which is often not enough to notice.
3) I suspect your code doesn't solve the problem as given. If you're only supposed to compress adjacent elements, your code doesn't do this. If you wanted to do what your code does with the official solution you could sort the list beforehand. Or you could use a map or hashtable to keep counts.
Generally speaking, the official solution is far better than yours in many ways. Again, you're asking for an opinion and this is mine.
Update
The official solution uses an auxiliary function named aux that takes three parameters: the currently accumulated sublist (some number of repetitions of the same value), the currently accumulated result (in reverse order), and the remaining input to be processed.
The invariant is that all the values in the first parameter (named current) are the same as the head value of the unprocessed list. Initially this is true because current is empty.
The function looks at the first two elements of the unprocessed list. If they're the same, it adds the first of them to the beginning of current and continues with the tail of the list (all but the first). If they're different, it wants to start accumulating a different value in current. It does this by adding current (with the one extra value added to the front) to the accumulated result, then continuing to process the tail with an empty value for current. Note that both of these maintain the invariant.
I remember that when I showed some code that I wrote to my professor he remarked, offhand, that
It rarely matters, but it's worth noting that fold* is a little bit more efficient than fold*' in SML/NJ, so you should prefer it over fold* when possible.
I forget whether fold* was foldr or foldl. I know that this is one of those micro-optimization things that probably doesn't make a big difference in practice, but I'd like to be in the habit of using the more efficient one when I have the choice.
Which is which? My guess is that this is SML/NJ specific and that MLton will be smart enough to optimize both down to the same machine code, but answers for other compilers are good to know.
foldl is tail-recursive, while foldr is not. Although you can do foldr in a tail-recursive way by reversing the list (which is tail recursive), and then doing foldl.
This is only going to matter if you are folding over huge lists.
Prefer the one that converts the given input into the intended output.
If both produce the same output such as with a sum, and if dealing with a list, folding from the left will be more efficient because the fold can begin with head element, while folding from the right will first require walking the list to find the last element before calculating the first intermediate result.
With arrays and similar random access data structures, there's probably not going to be much difference.
A compiler optimization that always chose the better of left and right would require the compiler to determine that left and right were equivalent over all possible inputs. Since foldl and foldr take a functions as arguments, this is a bit of a tall order.
I'm going to keep the accepted answer here, but I had the chance to speak to my professor, and his reply was actually the opposite, because I forgot a part of my question. The code in question was building up a list, and he said:
Prefer foldr over foldl when possible, because it saves you a reverse at the end in cases where you're building up a list by appending elements during the fold.
As in, for a trivial example:
- val ls = [1, 2, 3];
val ls = [1,2,3] : int list
- val acc = (fn (x, xs) => x::xs);
val acc = fn : 'a * 'a list -> 'a list
- foldl acc [] ls;
val it = [3,2,1] : int list
- foldr acc [] ls;
val it = [1,2,3] : int list
The O(n) save of a reverse is probably more important than the other differences between foldl and foldr mentioned in answers to this question.
sorry if this question has already been asked, I didn't find it. And sorry for my poor english.
I'm learning Haskell and try to use lists.
I wrote a function which transforms a list following a specific pattern, I can't check if it works now, but i think so.
This function is not a tail call function, so I think it will be horrible to compute this function with a big list:
transform :: [Int] -> [Int]
transform list = case list of
(1:0:1:[]) -> [1,1,1,1]
(1:1:[]) -> [1,0,1]
[1] -> [1,1]
(1:0:1:0:s) -> 1:1:1:1: (transform s)
(1:1:0:s) -> 1:0:1: (transform s)
(1:0:s) -> 1:1: (transform s)
(0:s) -> 0: (transform s)
So I thought about another function, which would be "better":
transform = reverse . aux []
where
aux buff (1:0:[1]) = (1:1:1:1:buff)
aux buff (1:[1]) = (1:0:1:buff)
aux buff [1] = (1:1:buff)
aux buff (1:0:1:0:s) = aux (1:1:1:1:buff) s
aux buff (1:1:0:s) = aux (1:0:1:buff) s
aux buff (1:0:s) = aux (1:1:buff) s
aux buff (0:s) = aux (0:buff) s
The problem is that I don't know how it compiles and if I'm wrong with the second function. Can you explain me how lists work ? Is it better to use (++) or reverse the list at the end ?
Thank you in advance for your answers
The first function is perfectly fine and in my opinion preferable to the second one.
The reason is laziness. If you have a transform someList expression in your code, the resulting list will not be evaluated unless you demand it. In particular the list will be evaluated only as far as it is needed; print $ take 10 $ transform xs will do less work than print $ take 20 $ transform xs.
In a strict language transform would indeed encumber the stack, since it would have to evaluate the whole list (in a non-tail recursive way) before returning anything of use. In Haskell transform (0:xs) evaluates to 0 : transform xs, a usable partial result. We can inspect the head of this result without touching the tail. There is no danger of stack overflow either: at any time there is at most a single unevaluated thunk (like transform xs in the previous example) in the tail of the list. If you demand more elements, the thunk will be just pushed further back, and the stack frame of the previous thunk can be garbage collected.
If we always fully evaluate the list then the performance of the two functions should be similar, or even then the lazy version could be somewhat faster because of the lack of reversing or the extra ++-s. So, by switching to the second function we lose laziness and gain no extra performance.
Your first version looks much better to me1. It's fine that it's not tail-recursive: you don't want it to be tail-recursive, you want it to be lazy. The second version can't produce even a single element without processing the entire input list, because in order to reverse the result of aux, the entirety of aux must be known. However,
take 10 . transform $ cycle [1,0,0,1,1,1]
would work fine with your first definition of transform, because you only consume as much of the list as you need in order to make a decision.
1 But note that (1:0:1:[]) is just [1,0,1].
I'm pretty new to Haskell and still trying to learn the ropes. My problem is this:
I am trying to take all of the numbers which when added to the number after it in a list is less than a certain number. In a more formal sense, how can I use sublists of my list as arguments for my filtering boolean function?
For example: we have the list [a0,a1,a2,...], how can I take from the list while a_n + a_(n+1) < c (where c is just some number)?
Ultimately I am going to be using this to create a sequence of root approximations of a function. Currently I have an infinite list of approximations (since I don't know where to stop yet) and I would like to take all of the approximations up until an approximation that has some tolerable error. The error of the approximation p_n is given as a function of p_n, p_(n-1), p_(n-2). Lets call this function f. So ideally I would like to keep taking elements from the list while
f(p_(n),p_(n-1),p_(n-2)) > error.
The signature of the function you want to write looks like this
takeLessThan :: (Num a, Ord a) => a -> [a] -> [a]
takeLessThan bound xs = ...
You can extract each pair of the list by zipping the list with the tail of itself.
pairs :: [b] -> [(b, b)]
pairs xs = zip xs (tail xs)
So the pairs of the list [1,2,3,4,5] will give you a tuple of (an, an+1).
[(1,2),(2,3),(3,4),(4,5)]
From there you can use the filter function from the Prelude to select the elements you want based on the function (a -> Bool).
filter :: (a -> Bool) -> [a] -> [a]
I think its easier to break down your problem into multiple steps intead of trying to solve it all at once with a super smart filtering function.
Start with a list [a0 ... an]
Turn it into a list of pairs [ (a0, a1) ... (a_n-1, an) ] with zip
Filter the interesting pairs with takeWhile (or filter, depending on what you want to do).
Turn the list of good pairs back into a list with just the first numbers using map
Don't worry about performance or about generating wasteful intermediate lists. Everything should be efficiently created on demand due to the lazy evaluation.