This question already has answers here:
What is the point of the diamond operator (<>) in Java?
(7 answers)
Closed 1 year ago.
Can you please point out where am I going wrong?
Works fine:
Arrays.sort(arr, (a, b) -> a[0] - b[0] );
error: array required, but Object found
PriorityQueue<int[]> pq = new PriorityQueue(10, ( (a, b) -> a[0] - b[0] ));
error: incompatible types: incompatible parameter types in lambda expression
PriorityQueue<int[]> pq = new PriorityQueue(10, ( (int[] a, int[] b) -> a[0] - b[0] ));
The argument requires arr.length which is an int, but you are passing an arr which I assume is the array.
Related
I'm new to Haskell. The following code shows a pair of integers. Let's say I want to sum up or subtract the pairs. How do I do that?
module IntPair where
data IntPair = IntPair Int Int
deriving(Show)
plusIntPair :: IntPair -> Int
plusIntPair = undefined
Let's say I created an IntPair 1 2.
I should get answer 3.
You need to use patterns to destructure your IntPair
Something like this should work (for the function):
plusIntPair :: IntPair -> Int
plusIntPair (IntPair a b) = a + b
In the snippet above, the first line declares that plusIntPair has type IntPair -> Int. The second line says that the function should destructure the data constructor IntPair, bind the first and second params to a and b respectively, and add them.
and to run it:
plusIntPair (IntPair 1 2)
(IntPair 1 2) constructs a value of type IntPair, plusIntPair is applied with the argument IntPair 1 2.
I have this matrix:
let arr = Array.make_matrix 4 4 0;;
and what to check if all elements are 0.
I heard of the function for_all but I can't quite figure it out how to use it with a matrix, since it expects an int array or a int list.
According to the documentation (https://caml.inria.fr/pub/docs/manual-ocaml/libref/Array.html), here is everything you need to know:
val for_all : ('a -> bool) -> 'a array -> bool
Array.for_all p [|a1; ...; an|] checks if all elements of the array satisfy the predicate p. That is, it returns (p a1) && (p a2) && ... && (p an).
Example: Array.for_all ((=) 0) has type int array -> bool and checks if all elements are zero.
A matrix is an array of arrays (or an array of rows if you prefer). So you need to execute a for_all on each one of the rows to check that all elements of the row are zero, and another outer for_all to check that all the for_alls over rows are true:
let arr = Array.make_matrix 4 4 0 in
Array.for_all (fun row ->
Array.for_all ((=) 0) row) arr
The shorthand for declaration and initialization in go is
var a, b, c = 1 , 2, 3
Equivalent to following way of declaration and initialization (as per specs)
a:=1
b:=2
c:=3
var a int
var b int
var c int
a=1
b=2
c=3
But I am not getting the answer for the problem found in following code:
package main
import "fmt"
func main() {
var a int = 0
var b int = 1
fmt.Println("init a ",a)
fmt.Println("init b ",b)
a, b = b, a+b
fmt.Println("printing a after `a, b = b, a+b`",a)
fmt.Println("printing b after `a, b = b, a+b`",b)
}
Output should be:
printing a after 'a, b = b, a+b' 1
printing b after 'a, b = b, a+b' 2
Since the value of b is evaluated with a + b i.e 1+1 = 2. But its giving 1.
Here is the playground links of both the working code where you can observe the difference.
a,b = b, a+b
a=b, b=a+b
I know I am missing something to understand, basically how the shorthand expression are evaluated especially when the same variable is involved in the expression.
But where is the proper documentation to refer. Could anyone help on this?
See here
The assignment proceeds in two phases. First, the operands of index
expressions and pointer indirections (including implicit pointer
indirections in selectors) on the left and the expressions on the
right are all evaluated in the usual order. Second, the assignments
are carried out in left-to-right order.
Based on that a+b (0+1) is evaluated first. Then it's assigned. Thus you get the result of a = 1 and b = 1
I am defining some functions in an Erlang script file and calling them in main to demonstrate their correctness. I have not had any problems up to now, but suddenly I'm getting an error for no real reason. Here is the code in question (I have checked that this line is the problem by commenting it out):
fibSeq() -> [0] ++ [1] ++ lists:zipwith(func(X, Y) -> X + Y end, fibs(), lists:delete(0, fibSeq())).
The idea behind this function is to efficiently calculate the Fibonacci sequence. It's possible the error is arising because of the infinite recursive nature of the function, however I believe I read that Erlang uses lazy evaluation, so I feel like this should work.
Edit: The usage of this would be list:sublist(fibSeq(), N) or list:nth(N, fibSeq()) where N is an integer.
Edit 2:
The error message is "Syntax error before '->'" with reference to the line number one above the fibSeq() function, and the code before it is
merge([], []) -> [];
merge(A, []) -> A;
merge([], B) -> B;
merge([A|As], [B|Bs]) when A < B -> [A] ++ merge(As, [B] ++ Bs);
merge([A|As], [B|Bs]) -> [B] ++ merge([A] ++ As, Bs).
mergesort([]) -> [];
mergesort([A]) -> [A];
mergesort(As) ->
merge(mergesort(lists:sublist(As, length(As) div 2)), mergesort(lists:sublist(As, length(As) div 2 + 1, length(As) div 2 + 1))).
I have changed my fibonacci code to use a different linear evaluation that I thought of shortly after:
fib(N) when N >= 0, is_integer(N) -> fibHelp(0, 1, N).
fibHelp(L, _, 0) -> L;
fibHelp(L, H, A) when A > 0, is_integer(L), is_integer(H), is_integer(A) ->
fibHelp(H, L+H, A - 1).
The syntax for higher order functions in erlang is fun(X) -> X * 2 end. Using func is a syntax error.
Here's the problem at hand: I need to find the largest difference between adjacent numbers in a list using recursion. Take the following list for example: [1,2,5,6,7,9]. The largest difference between two adjacent numbers is 3 (between 2 and 5).
I know that recursion may not be the best solution, but I'm trying to improve my ability to use recursion in Haskell.
Here's the current code I currently have:
largestDiff (x:y:xs) = if (length (y:xs) > 1) then max((x-y), largestDiff (y:xs)) else 0
Basically - the list will keep getting shorter until it reaches 1 (i.e. no more numbers can be compared, then it returns 0). As 0 passes up the call stack, the max function is then used to implement a 'King of the Hill' type algorithm. Finally - at the end of the call stack, the largest number should be returned.
Trouble is, I'm getting an error in my code that I can't work around:
Occurs check: cannot construct the infinite type:
t1 = (t0, t1) -> (t0, t1)
In the return type of a call of `largestDiff'
Probable cause: `largestDiff' is applied to too few arguments
In the expression: largestDiff (y : xs)
In the first argument of `max', namely
`((x - y), largestDiff (y : xs))'
Anyone have some words of wisdom to share?
Thanks for your time!
EDIT: Thanks everyone for your time - I ended up independently discovering a much simpler way after much trial and error.
largestDiff [] = error "List too small"
largestDiff [x] = error "List too small"
largestDiff [x,y] = abs(x-y)
largestDiff (x:y:xs) = max(abs(x-y)) (largestDiff (y:xs))
Thanks again, all!
So the reason why your code is throwing an error is because
max((x-y), largestDiff (y:xs))
In Haskell, you do not use parentheses around parameters and separate them by commas, the correct syntax is
max (x - y) (largestDiff (y:xs))
The syntax you used is getting parsed as
max ((x - y), largestDiff (y:xs))
Which looks like you're passing a tuple to max!
However, this does not solve the problem. I always got 0 back. Instead, I would recommend breaking up the problem into two functions. You want to calculate the maximum of the difference, so first write a function to calculate the differences and then a function to calculate the maximum of those:
diffs :: Num a => [a] -> [a]
diffs [] = [] -- No elements case
diffs [x] = [] -- One element case
diffs (x:y:xs) = y - x : diffs (y:xs) -- Two or more elements case
largestDiff :: (Ord a, Num a) => [a] -> a
largestDiff xs = maximum $ map abs $ diffs xs
Notice how I've pulled the recursion out into the simplest possible case. We didn't need to calculate the maximum as we traversed the list; it's possible, just more complex. Since Haskell has a handy built-in function for calculating the maximum of a list for us, we can also leverage that. Our recursive function is clean and simple, and it is then combined with maximum to implement the desired largestDiff. As an FYI, diffs is really just a function to compute the derivative of a list of numbers, it can be a very useful function for data processing.
EDIT: Needed Ord constraint on largestDiff and added in map abs before calculating maximum.
Here's my take at it.
First some helpers:
diff a b = abs(a-b)
pick a b = if a > b then a else b
Then the solution:
mdiff :: [Int] -> Int
mdiff [] = 0
mdiff [_] = 0
mdiff (a:b:xs) = pick (diff a b) (mdiff (b:xs))
You have to provide two closing clauses, because the sequence might have either even or odd number of elements.
Another solution to this problem, which circumvents your error, can be obtained
by just transforming lists and folding/reducing them.
import Data.List (foldl')
diffs :: (Num a) => [a] -> [a]
diffs x = zipWith (-) x (drop 1 x)
absMax :: (Ord a, Num a) => [a] -> a
absMax x = foldl' max (fromInteger 0) (map abs x)
Now I admit this is a bit dense for a beginner, so I will explain the above.
The function zipWith transforms two given lists by using a binary function,
which is (-) in this case.
The second list we pass to zipWith is drop 1 x, which is just another way of
describing the tail of a list, but where tail [] results in an error,
drop 1 [] just yields the empty list. So drop 1 is the "safer" choice.
So the first function calculates the adjacent differences.
The name of the second function suggests that it calculates the maximum absolute
value of a given list, which is only partly true, it results in "0" if passed an
empty list.
But how does this happen, reading from right to left, we see that map abs
transforms every list element to its absolute value, which is asserted by
the Num a constraint. Then the foldl'-function traverses the list and
accumulates the maximum of the previous accumulator and the current element of
the list traversal. Moreover I'd like to mention that foldl' is the "strict"
sister/brother of the foldl-function, where the latter is rarely of use,
because it tends to build up a bunch of unevaluated expressions called thunks.
So let's quit all this blah blah and see it in action ;-)
> let a = diffs [1..3] :: [Int]
>>> zipWith (-) [1,2,3] (drop 1 [1,2,3])
<=> zipWith (-) [1,2,3] [2,3]
<=> [1-2,2-3] -- zipWith stops at the end of the SHORTER list
<=> [-1,-1]
> b = absMax a
>>> foldl' max (fromInteger 0) (map abs [-1,-1])
-- fromInteger 0 is in this case is just 0 - interesting stuff only happens
-- for other numerical types
<=> foldl' max 0 (map abs [-1,-1])
<=> foldl' max 0 [1,1]
<=> foldl' max (max 0 1) [1]
<=> foldl' max 1 [1]
<=> foldl' max (max 1 1) []
<=> foldl' max 1 [] -- foldl' _ acc [] returns just the accumulator
<=> 1