Haskell Criterion - 'nf' is applied to too few arguments - haskell

I am a new guy to Haskell. I am working a benchmark(Criteriaon) on binary search algorithm. I keep getting error: 'nf' is applied to too few arguments what am I doing wrong.
Thanks
binSear array serNum lowInx highInx
| highInx < lowInx = -1
| array!!sred > serNum = binSear array serNum lowInx (mid-1)
| array!!sred < serNum = binSear array serNum (mid+1) highInx
| otherwise = mid
where
mid = lowInx + ((highInx - lowInx) `div` 2)
main = do
let arr = [1..10000000]
defaultMain [
bench "1" $ nf (binSear arr 54527 0 9999999)
]

The type of nf is (a->b)->a->b, so it expects two parameters: a function and an input to that function. The function should produce a Benchmarkable.
In your case, you are just passing one parameter to nf: the function itself, but that function is fully applied, so it's not expecting any additional parameter, nor are you passing that extra parameter. In this case, you should partially apply the function and pass that extra parameter to nf.
You may be forced to reorder the parameters of binSear or create a helper lambda to do so, to ensure that the currying happens in the last parameter, and you should pass that parameter to nf outside of the parenthesis.

Related

Variable not in scope when using where clause and guard pattern matching

Let's say I have this piece of code:
data Command = Forward Integer
| Backwards Integer
doSomething givenCommand
| Forward value <- givenCommand = undefined
where calculatedValue = sqrt value
Let's say the undefined line, which would use the calculatedValue, is going to be really long and the calculatedValue calculation also much longer, so to make the code more readable, I'd like to use a where clause.
The problem is that the variable value, specified in the guard pattern match, is not in scope for the where clause.
Is there a way around this, which wouldn't force me to perform the calculation on the guard line ?
Thanks.
value is indeed not in the scope of where since it is not said that the given pattern guard will "fire". If the pattern fails, then there is no value, so that makes not much sense.
You can use a let … in … clause here:
doSomething givenCommand
| Forward value <- givenCommand = let calculatedValue = sqrt value in undefined
| … = …
you here however do not need a pattern guard, you can pattern match in the head of the doSomething function:
doSomething (Forward value) = undefined
where calculatedValue = sqrt value
doSomething (…) = …

How To Understand THE Following Code Snippet?

i came up with understanding confusion , what will be the right explanation for this code?
a = [(0,1),(1,2),(2,3)]
result = sum(n for _,n in a)
print(result)
I guess that your confusion is coming from the , and the fact that sum also accepts a second argument.
In this case, only one argument is passed to sum because that line is evaluated as
result = sum(n for (_, n) in a)
This line simply sums all the second elements in the list of tuples, and it is equivalent to the following:
list_of_tuples = [(0,1),(1,2),(2,3)]
total = 0
for (first_element, second_element) in list_of_tuples:
total += second_element
print(total)
Technically _ is a normal, valid identifier name, but the convention is to use it for values that are disregarded in the next part of the code.
I think another way of thinking of it is:
result=0
for _,n in a:
result += n
You can substitute "_,n" for any other two variables like "x,y" for example.

haskell: factors of a natural number

I'm trying to write a function in Haskell that calculates all factors of a given number except itself.
The result should look something like this:
factorlist 15 => [1,3,5]
I'm new to Haskell and the whole recursion subject, which I'm pretty sure I'm suppoused to apply in this example but I don't know where or how.
My idea was to compare the given number with the first element of a list from 1 to n div2
with the mod function but somehow recursively and if the result is 0 then I add the number on a new list. (I hope this make sense)
I would appreciate any help on this matter
Here is my code until now: (it doesn't work.. but somehow to illustrate my idea)
factorList :: Int -> [Int]
factorList n |n `mod` head [1..n`div`2] == 0 = x:[]
There are several ways to handle this. But first of all, lets write a small little helper:
isFactorOf :: Integral a => a -> a -> Bool
isFactorOf x n = n `mod` x == 0
That way we can write 12 `isFactorOf` 24 and get either True or False. For the recursive part, lets assume that we use a function with two arguments: one being the number we want to factorize, the second the factor, which we're currently testing. We're only testing factors lesser or equal to n `div` 2, and this leads to:
createList n f | f <= n `div` 2 = if f `isFactorOf` n
then f : next
else next
| otherwise = []
where next = createList n (f + 1)
So if the second parameter is a factor of n, we add it onto the list and proceed, otherwise we just proceed. We do this only as long as f <= n `div` 2. Now in order to create factorList, we can simply use createList with a sufficient second parameter:
factorList n = createList n 1
The recursion is hidden in createList. As such, createList is a worker, and you could hide it in a where inside of factorList.
Note that one could easily define factorList with filter or list comprehensions:
factorList' n = filter (`isFactorOf` n) [1 .. n `div` 2]
factorList'' n = [ x | x <- [1 .. n`div` 2], x `isFactorOf` n]
But in this case you wouldn't have written the recursion yourself.
Further exercises:
Try to implement the filter function yourself.
Create another function, which returns only prime factors. You can either use your previous result and write a prime filter, or write a recursive function which generates them directly (latter is faster).
#Zeta's answer is interesting. But if you're new to Haskell like I am, you may want a "simple" answer to start with. (Just to get the basic recursion pattern...and to understand the indenting, and things like that.)
I'm not going to divide anything by 2 and I will include the number itself. So factorlist 15 => [1,3,5,15] in my example:
factorList :: Int -> [Int]
factorList value = factorsGreaterOrEqual 1
where
factorsGreaterOrEqual test
| (test == value) = [value]
| (value `mod` test == 0) = test : restOfFactors
| otherwise = restOfFactors
where restOfFactors = factorsGreaterOrEqual (test + 1)
The first line is the type signature, which you already knew about. The type signature doesn't have to live right next to the list of pattern definitions for a function, (though the patterns themselves need to be all together on sequential lines).
Then factorList is defined in terms of a helper function. This helper function is defined in a where clause...that means it is local and has access to the value parameter. Were we to define factorsGreaterOrEqual globally, then it would need two parameters as value would not be in scope, e.g.
factorsGreaterOrEqual 4 15 => [5,15]
You might argue that factorsGreaterOrEqual is a useful function in its own right. Maybe it is, maybe it isn't. But in this case we're going to say it isn't of general use besides to help us define factorList...so using the where clause and picking up value implicitly is cleaner.
The indentation rules of Haskell are (to my tastes) weird, but here they are summarized. I'm indenting with two spaces here because it grows too far right if you use 4.
Having a list of boolean tests with that pipe character in front are called "guards" in Haskell. I simply establish the terminal condition as being when the test hits the value; so factorsGreaterOrEqual N = [N] if we were doing a call to factorList N. Then we decide whether to concatenate the test number into the list by whether dividing the value by it has no remainder. (otherwise is a Haskell keyword, kind of like default in C-like switch statements for the fall-through case)
Showing another level of nesting and another implicit parameter demonstration, I added a where clause to locally define a function called restOfFactors. There is no need to pass test as a parameter to restOfFactors because it lives "in the scope" of factorsGreaterOrEqual...and as that lives in the scope of factorList then value is available as well.

Conversion from decimal to binary in Ocaml

I am trying to convert a given decimal value its corresponding binary form. I am using Ocaml about which I don't know much and am quite confused. So far I have the following code
let dec_to_bin_helper function 1->'T' | 0->'F'
let dec_to_bin x =
List.fold_left(fun a z -> z mod 2 dec_to_bin_helper a) [] a ;;
I must include here that I want my output to be in the form of a list of T's and F's where T's represent the binary 1's and F's represent binary 0's
If I try to run the above code it gives me an error saying "Error: This expression is not a function; it cannot be applied"
I understand that the part where I am calling the helper function is wrong... Any help in the matter would be appreciated!
I don't really understand your second function at all. You are folding an empty list, and your function takes an argument x which it never uses. Am I correct in assuming that you want to take a number and return a list of 'T's and 'F's which represent the binary? If that is the case, this code should work:
let dec_to_bin x =
let rec d2b y lst = match y with 0 -> lst
| _ -> d2b (y/2) ((dec_to_bin_helper (y mod 2))::lst)
in
d2b x [];;
This function inserts (x mod 2) converted into a T/F into a list, then recursively calls the function on x/2 and the list. When x = 0 the list is returned. If call it on 0 an empty list will be returned (I'm not sure if that's what you want or not).
I think the problem that you had is that you are treating lists as if they are mutable and thinking that fold mutates the list. That is not the case, fold just goes through each element in a list and applies a function to it. Since your list is empty it didn't do anything.

Why doesn't my Haskell function accept negative numbers?

I am fairly new to Haskell but do get most of the basics. However there is one thing that I just cannot figure out. Consider my example below:
example :: Int -> Int
example (n+1) = .....
The (n+1) part of this example somehow prevents the input of negative numbers but I cannot understand how. For example.. If the input were (-5) I would expect n to just be (-6) since (-6 + 1) is (-5). The output when testing is as follows:
Program error: pattern match failure: example (-5)
Can anyone explain to me why this does not accept negative numbers?
That's just how n+k patterns are defined to work:
Matching an n+k pattern (where n is a variable and k is a positive integer literal) against a value v succeeds if x >= k, resulting in the binding of n to x - k, and fails otherwise.
The point of n+k patterns is to perform induction, so you need to complete the example with a base case (k-1, or 0 in this case), and decide whether a parameter less than that would be an error or not. Like this:
example (n+1) = ...
example 0 = ...
The semantics that you're essentially asking for would be fairly pointless and redundant — you could just say
example n = let n' = n-1 in ...
to achieve the same effect. The point of a pattern is to fail sometimes.

Resources