Haskell parse error on input '=' - function

This is a Quicksort function. But I've got an error at 5:46
--sort function
quicksort [] = []
quicksort (x:xs) = (quicksort lesser) ++[x] ++ (quicksort greater)
where lesser = filter (<) xs
greater = filter (>=) xs
What's the problem?
It seems that the function is correct.

It appears you have a simple whitespace error.... lesser and greater need to be indented equally, so that they begin on the same column.

Related

How to map a function over a tree in haskell? [duplicate]

I am trying to do create a function that uses two lists. For some reason, when I pass:
isPermutation [] [], or [] [1,2,3] or [1,2,3] [] -
I get Non-exhaustive patterns in function isPermutation
isPermutation :: (Eq a)=>[a]->[a]->Bool
**isPermutaiton** [] [] = True
**isPermutaiton** [] ys = False
**isPermutation** xs [] = False
isPermutation (x:xs) (ys) = True
I cannot figure out why am I getting this since I am covering all cases!
UPDATE
*Thanks to Chris Taylor : - It was a simple typo. I had misspelled one of my function names "isPermutaiton" instead of "isPermutation" *
Be careful on your spelling since Haskell won't recognize that you are meaning the same function(duh) or that you are "declaring" 2 different functions with cases meshed up.
You have a typo in your second and third lines -- isPermutaiton instead of isPermutation.
You have effectively defined
foo [] [] = True -- both arguments empty
foo [] ys = False -- first argument empty, second argument anything
bar xs [] = False -- second argument empty, first argument anything
bar (x:xs) ys = True -- first argument at least one element, second anything
so whenever you call foo (i.e. isPermutaiton) with a non-empty first argument you will get an error, and whenever you call bar (i.e. isPermutation) with an empty first argument and a non-empty second argument you will get an error.

Type casting within a recursive function in Haskell

I am learning Haskell and recursion and different types in Haskell is making my brain hurt. I am trying to create a recursive function that will take a 32 bit binary number string and convert it to a decimal number. I think my idea for how the recursion will work is fine but implementing it into Haskell is giving me headaches. This is what I have so far:
bin2dec :: String -> Int
bin2dec xs = ""
bin2dec (x:xs) = bin2dec xs + 2^(length xs) * x
The function is supposed to take a 32 bit number string and then take off the first character of the string. For example, "0100101010100101" becomes "0" and "100101010100101". It then should turn the first character into a integer and multiply it by 2^length of the rest of the string and add it to the function call again. So if the first character in the 32 bit string is "1" then it becomes 1 * 2^(31) + recursive function call.
But, whenever I try to compile it, it returns:
traceProcP1.hs:47:14: error:
* Couldn't match type `[Char]' with `Int'
Expected: Int
Actual: String
* In the expression: ""
In an equation for `bin2dec': bin2dec xs = ""
|
47 | bin2dec xs = ""
| ^^
traceProcP1.hs:48:31: error:
* Couldn't match expected type `Int' with actual type `Char'
* In the second argument of `(+)', namely `2 ^ (length xs) * x'
In the expression: bin2dec xs + 2 ^ (length xs) * x
In an equation for `bin2dec':
bin2dec (x : xs) = bin2dec xs + 2 ^ (length xs) * x
|
48 | bin2dec (x:xs) = bin2dec xs + 2^(length xs) * x
| ^^^^^^^^^^^^^^^^^^
I know this has to do with changing the datatypes, but I am having trouble type casting in Haskell. I have tried type casting x with read and I have tried making guards that will turn the '0' into 0 and '1' into 1, but I am having trouble getting these to work. Any help would be very appreciated.
There is no casting. If you want to convert from one type to another, there needs to be a function with the right type signature to do so. When looking for any function in Haskell, Hoogle is often a good start. In this case, you're looking for Char -> Int, which has several promising options. The first one I see is digitToInt, which sounds about right for you.
But if you'd rather do it yourself, it's quite easy to write a function with the desired behavior, using pattern matching:
bit :: Char -> Int
bit '0' = 0
bit '1' = 1
bit c = error $ "Invalid digit '" ++ [c] ++ "'"

expr is giving unexpected results

expr is giving unexpected results for 4 characters (t, n, f, y). And if you are doing some further calculation. then code is breaking. I could not understand why this is happening?
% expr (F)
F
% expr (F)*1
can't use non-numeric string as operand of "*"
And,
% expr (t)
t
% expr (n)
n
% expr (f)
f
% expr (y)
y
This is coming file for charcters : t, n, f, y. There are no variables named by these characters. It should flag variable not found or some other valid error. Am i missing some thing?
The [expr] conditions of commands such as [if] and [while] expect the expression to evaluate to a boolean, i.e., an integer or one of the following string values:
true, on, yes
false, off, no
I believe t, y, f and n are shortcuts for these.
I think you are expecting something wrong from expr.
That command is intended for evaluating expressions. It can do arithmetical operations on number, compare strings or number, execute some mathematical functions, and such.
Your lines
% expr (F)
% expr (t)
% expr (n)
% expr (f)
% expr (y)
all do the same thing: they ask to perform no operation on a literal string with higher precedence (the braces). So? There is nothing more and expr returns the string itself.
In
% expr (F)*1
however, you are trying to multiply a string to a number: an operation which is not defined. Indeed, expr gives you an error saying that one of the operands of * is a non numeric string (which number F should represent?).
With a literal string such F, or y, you can ask string comparison. For example, you can do these:
% expr F < f
1
(because in my encoding the upper case letters come before lower case ones)
% expr F == y
0
and so on.
So, expr is not giving any unexpected result, but maybe your expectations are wrong.

Function definition in Haskell

I'm beginning to learn Haskell with "Learn You a Haskell for Great Good!" and I've made a strange mistake, which I can't find the reason for.
Here is the code I typed:
let xs = [if x < 3 then "bang" else "boom" | x <- xs]
And the the text of the error in GHCi:
No instance for (Num [Char])
arising from the literal `3'
Possible fix: add an instance declaration for (Num [Char])
In the second argument of `(<)', namely `(3)'
In the expression: x < (3)
In the expression: if x < (3) then "bang" else "boom"
But when I type:
let boom xs = [if x < 3 then "bang" else "boom" | x <- xs]
which is the example of the book, I don't have any problem.
Could someone explain my mistake?
Your definition of xs is recursive, that is you're using xs inside its own definition. I don't think that's what you intended.
Since you're using "bang" and "boom" inside the list comprehensions, Haskell knows that xs must be a list of strings (because xs is equal to the result of the list comprehension). Further you say that x is an element of xs (x <- xs), so x must be a String (a.k.a. [Char]). However you do x < 3, which implies that x is a number. The error message means "a String is not a number".
Try to give the expression a type.
xs = [if x < 3 then "bang" else "boom" | x <- xs]
So xs is a list, we don't know yet what type its elements have, so let's look at that next. The list elements are
if x < 3 then "bang" else "boom"
which is an expression of type String (aka [Char]).
So xs :: [String]. Since the x from the expression describing the list elements is taken from the list xs itself, it is a String too, and is used in the comparison
if x < 3
Now, 3 is an integer literal, thus it is polymorphic and has type
3 :: Num a => a
So from the expression x < 3, we have
a Num constraint from the literal,
the type String from the fact that x is drawn from a list of Strings.
Thus we need a Num instance for String to have a well-typed expression.
Usually, there is no Num instance for String (what would a useful one look like?), so you get a type error.
If xs is the argument of a function,
boom xs = [if x < 3 then "bang" else "boom" | x <- xs]
there is no reason why the type of x should be String, hence that works.
let xs = ...
means xs equals a list of "bang"s and/or "boom"s, but the condition states that those elements should be tested for <3, which is usually done with numbers, not strings.
let boom xs =...
equates the function 'boom' with the right hand side of the equation, where the parameter 'xs' is the list from which the elements to be tested for <3 are drawn.

OCaml: Using a comparison operator passed into a function

I'm an OCaml noob. I'm trying to figure out how to handle a comparison operator that's passed into a function.
My function just tries to pass in a comparison operator (=, <, >, etc.) and an int.
let myFunction comparison x =
if (x (comparison) 10) then
10
else
x;;
I was hoping that this code would evaluate to (if a "=" were passed in):
if (x = 10) then
10
else
x;;
However, this is not working. In particular, it thinks that x is a bool, as evidenced by this error message:
This expression has type 'a -> int -> bool
but an expression was expected of type int
How can I do what I'm trying to do?
On a side question, how could I have figured this out on my own so I don't have to rely on outside help from a forum? What good resources are available?
Comparison operators like < and = are secretly two-parameter (binary) functions. To pass them as a parameter, you use the (<) notation. To use that parameter inside your function, you just treat it as function name:
let myFunction comp x =
if comp x 10 then
10
else
x;;
printf "%d" (myFunction (<) 5);; (* prints 10 *)
OCaml allows you to treat infix operators as identifiers by enclosing them in parentheses. This works not only for existing operators but for new ones that you want to define. They can appear as function names or even as parameters. They have to consist of symbol characters, and are given the precedence associated with their first character. So if you really wanted to, you could use infix notation for the comparison parameter of myFunction:
Objective Caml version 3.12.0
# let myFunction (#) x =
x # 10;;
val myFunction : ('a -> int -> 'b) -> 'a -> 'b = <fun>
# myFunction (<) 5;;
- : bool = true
# myFunction (<) 11;;
- : bool = false
# myFunction (=) 10;;
- : bool = true
# myFunction (+) 14;;
- : int = 24
#
(It's not clear this makes myFunction any easier to read. I think definition of new infix operators should be done sparingly.)
To answer your side question, lots of OCaml resources are listed on this other StackOverflow page:
https://stackoverflow.com/questions/2073436/ocaml-resources
Several possibilities:
Use a new definition to redefine your comparison operator:
let myFunction comparison x =
let (#) x y = comparison x y in
if (x # 10) then
10
else
x;;
You could also pass the # directly without the extra definition.
As another solution you can use some helper functions to define what you need:
let (/*) x f = f x
let (*/) f x = f x
let myFunction comparison x =
if x /* comparison */ 10 then
10
else
x