I'm trying out an exercise where I have to print out a root node of a bst. They are telling me to use data BinSearch x y = Empty | Node x y (BinSearch x y) (BinSearch x y) (meaning a binary search tree either has nothing in it or it does) and the signature, result :: BinSearch x y -> Maybe y. I need to run the program like,
> result None
Nothing
> result (Node 0 44 None None)
Just 44
I'm a bit confused on how to do this. If I had control over the signature, it'd be easy, but I don't understand how to go about this.
The only thing I've come up with is
data BinSearch x y = None | Node x y (BinSearch x y) (BinSearch x y)
result :: BinSearch x y -> Maybe y
result (Node a b None None) = b
but the error I get there is that it couldn't match v with BinSearch x0 y0.
EDIT: I have fixed all transcription errors, apologies. The problem is now stated EXACTLY as it was in the book.
Two small hints: first, it must be BinSearch with a capital B. I suspect this was a transcription error on your part. Second is a syntax hint; your pattern needs parentheses, like this:
result (Node a b None None) = ...
This is not a complete solution; but will get you over this hurdle and into the next (more interesting) error.
I got it. I'm dumb. You just have to put "Just 44" at the end. My problem was that I didn't know that "Just" was built in.
Related
Exercise
Hello every one!
I have been struggling to get this function working in the specific way they want.
I tried everything and the only output I could make was without the starting and ending point, eg: [((a,b),(b,c))]
Could someone please give me some help? I am stucked...
Update: type Point = (Float, Float)
Well since you got it working without the starting/ending point. An easy way to complete would be use your function but add the starting/ending point in the list in an inner function. So your interface is still same.
Another way using recursion, pattern matching and guards is:
-- assuming the inputs to be int as definition of point not given
solve x z [] = [(x,z)]
solve x z (y:ys)
| x == 0 = solve y z ys -- x ==0 to be replaced by null/empty condition on x
| null ys && z == 0 = [] -- z ==0 to be replaced by null/empty condition on z
| null ys = [(y, z)]
| otherwise = (x,y) : solve y z ys
Added a base case when the list is empty or start/end points not valid based on darthfennec comment.
f x zero = Nothing
f x y = Just $ x / y
where zero = 0
The literal-bound identifier zero simply matches all after the warning Pattern match(es) are overlapped.
That's how Haskell's syntax works; every lowercase-initial variable name in a pattern (re)binds that name. Any existing binding will be shadowed.
But even if that weren't the case, the binding for zero would not be visible to the first alternative, because of how Haskell's syntax works. A similar thing happens in the following version:
f = \v1 v2 -> case (v1, v2) of
(x, zero) -> Nothing
(x, y) -> Just $ x / y
where zero = 0
The where clause only applies to the one alternative that it's part of, not to the whole list of alternatives. That code is pretty much the same thing as
f = \v1 v2 -> case (v1, v2) of
(x, zero) -> Nothing
(x, y) -> let zero = 0 in Just $ x / y
If bound identifiers had different semantics than unbound identifiers in a pattern match, that could be quite error prone as binding a new identifier could mess up pattern matches anywhere that identifier is in scope.
For example let's say you're importing some module Foo (unqualified). And now the module Foo is changed to add the binding x = 42 for some reason. Now in your pattern match you'd suddenly be comparing the first argument against 42 rather than binding it to x. That's a pretty hard to find bug.
So to avoid this kind of scenario, identifier patterns have the same semantics regardless of whether they're already bound somewhere.
Because they are very fragile. What does this compute?
f x y z = 2*x + 3*y + z
Would you expect this to be equal to
f x 3 z = 2*x + 9 + z
f _ _ _ = error "non-exhaustive patterns!"
only because there's a y = 3 defined somewhere in the same 1000+ line module?
Also consider this:
import SomeLibrary
f x y z = 2*x + 3*y + z
What if in a future release SomeLibrary defines y? We don't want that to suddenly stop working.
Finally, what if there is no Eq instance for y?
y :: a -> a
y = id
f :: a -> (a -> a) -> a
f x y = y x
f x w = w (w x)
Sure, it is a contrived example, but there's no way the runtime can compare the input function to check whether it is equal to y or not.
To disambiguate this, some new languages like Swift uses two different syntaxes. E.g. (pseudo-code)
switch someValue {
case .a(x) : ... // compare by equality using the outer x
case .b(let x) : ... // redefine x as a new local variable, shadowing the outer one
}
zero is just a variable that occurs inside a pattern, just like y does in the second line. There is no difference between the two. When a variable that occurs inside a pattern, this introduces a new variable. If there was a binding for that variable already, the new variable shadows the old one.
So you cannot use an already bound variable inside a pattern. Instead, you should do something like that:
f x y | y == zero = Nothing
where zero = 0
f x y = Just $ x / y
Notice that I also moved the where clause to bring it in scope for the first line.
How to indent correctly a nested case expression in haskell that would act like a nested loop in imperative programming ?
f x y = case x of
1 -> case y of
1 ->
2 ->
...
2 -> case y of
...
The compiler gives me an indentation error at the start of the second x case, so i'm guessing it doesn't understand that the first x case is over
Not directly an answer, but could maybe helpful nevertheless:
In this particular case, you could also write:
f 1 1 = ...
f 1 2 = ...
f 2 2 = ...
or, as a case expression:
f x y = case (x, y) of
(1,1) -> ...
(1,2) -> ...
(2,1) -> ...
Your code seems ok. Haskell has a very simple rule of Indenation as explained in wikibooks:
Code which is part of some expression should be indented further in
than the beginning of that expression.
This works for me:
f x y = case x of
1 -> case y of
1 -> undefined
2 -> undefined
2 -> case y of
1 -> undefined
You may want to check your editor to see if it is doing proper indentation. As #Tarmil suggested, always use spaces for indentation. More details on that here.
I had the same problem and it was due to that I was using tabs for identation. When I indentated the code with spaces, it worked!
At HaskellWiki's Do notation considered harmful, section Useful applications, I found:
It shall be mentioned that the do sometimes takes the burden from you
to write boring things.
E.g. in
getRight :: Either a b -> Maybe b
getRight y =
do Right x <- y
return x
a case on y is included, which calls fail if y is not a Right (i.e.
Left), and thus returns Nothing in this case.
Calling fail (Nothing) on a pattern mismatch sounds interesting, so I wanted to try this out. However, the syntax looks wrong - we're not in the Either monad, so how can we extract anything from y?
Indeed, I tried and it gave me "Couldn't match type `Either a' with `Maybe'". So let's use the correct pattern matcher, let in here:
getRight y = do { let (Right x) = y; return x }
That gave me a syntax error "parse error on input `}'". Not that I understand why this doesn't work, but let's write it out in multiline notation:
getRight y = do
let (Right x) = y
return x
Ah, that seemed to work - parse at least. However:
*Main> getRight (Right 5)
Just 5
*Main> getRight (Left 5)
Just *** Exception: […]\test.hs:16:13-25: Irrefutable pattern failed for pattern (Data.Either.Right x)
-- `Nothing` was expected
What gives? So my questions are now:
What happened here? Why did my semicolon-brace line not work?
How to do it correctly (with do, everything else is trivial)?
The example is probably meant to be
getRight :: Either a b -> Maybe b
getRight y =
do Right x <- return y -- note: return = Just
return x
where the pattern match failure calls fail = const Nothing. It is translated into:
getRight y = let ok (Right x) = do {return x}
ok _ = fail "pattern mismatch error"
in return y >>= ok
FWIW most experienced folks seem to think fail as a Monad method was a wart. Check out MonadPlus for a maybe more principled approach to failure.
I'm trying to implement a function using list comprehensions that copies an element an amount of times as specified. I'm really stuck on this but I'm trying to
for example
copy 2 'a' = aa
This is what I have so far:
copy2 :: Int->a->[a]
copy2 x y = func1 y [b|b<-[1..x]]
where func1 is somehow mapping y to every element of x
It's not a lot but I'm really clueless on this one sorry guys.
Even though an answer has been accepted, I want to point out that you said something profoundly important in your very question, which could have led you to an answer.
You said:
copy2 :: Int->a->[a]
copy2 x y = func1 y [b|b<-[1..x]]
where func1 is somehow mapping y to every element of x
If we clean up the phrasing a bit -- I am sure it's what you meant -- we actually want something that maps every element of the list produced by the comprehension to the constant value y.
Well, making a function that produces a value y for a single x is simple:
const y x = y
In fact, the function is useful enough that it exists in the Prelude already!
Now we just need to map over every element of the list.
copy2 x y = map (const y) [b | b <- [1..x]]
or a bit simplified, to really show how close we are to your original description, (even though I know you needed the list comprehension)
copy2 x y = map (\x -> y) [1..x]
"map x to y for every x."
So you see, you had it all along.
copy2 qty item = [item|_<-[1..qty]]