I'm a little new to Haskell, but this behavior is bizarre to me. If I have a simple function defined as follows:
foobar :: Integer -> [Integer] -> Integer
foobar x y = case y of
(a:x:b) -> x
_ -> -1
I'm basically expecting that the function should evaluate to the first argument of foobar if y contains at least two elements and the second element of y is just the first argument of foobar. Otherwise get a -1. But in ghci:
foobar 5 [6,7]
gives me 7, not -1.
How do I make sense of this behavior?
What you are doing here is not "updating" the x variable but shadowing it.
You are creating a new variable called x in the scope of the first branch of
your case statement.
You cannot use a case statement to compare equality as I believe you are
trying to do. If that is your goal, you will need to do something like
foobar :: Integer -> [Integer] -> Integer
foobar x y = case y of
(a:x':b) | x == x' -> x
_ -> -1
You can tell that x is not destructively updated by adjusting your code like so:
foobar :: Integer -> [Integer] -> Integer
foobar x y = (case y of
(a:x:b) -> x
_ -> -1
) + x
The x at the end will use the original x value; it is not destroyed, rather, the x binding inside the case expression is shadowed. Calling foobar 5 [6,7] will produce 12, not 14.
Related
I've got this piece of code that is supposed to check whther or not first elemnt of an array can be divided by the seocnd one. Have been struggling for some time now with finding the solution, as after compiling i get this error:
Parse error (line 2, column 22): parse error (possibly incorrect indentation or mismatched brackets)
Indentation is quite confusing to me as I'm quite new to Haskell, any help would be appreciated with determining what should I do here
fst2Div:: [a] -> Bool
fst2Div (x : y : _) =
case theList of (x:_:_) -> x
(_:y:_) -> y
if (y `mod` x)==0 then True
else False
x and y are already in scope by the (x : y : _) pattern. There is no need to use an extra case … of … expression. This will not work here anyway, since the case … of … expression will return either x or y. Furthermore theList not defined.
The signature is furthermore to generic. a can be of any type. But you can only calculate the mod :: Integral a => a -> a -> a on an Integral type. You thus can work with x and y directy with:
fst2Div:: Integral a => [a] -> Bool
fst2Div (x : y : _) = y `mod` x == 0
fst2Div _ = False
The second clause unifies with lists that have less than two elements. In that case we here return False.
Hello everyone I'm trying to implement the higher-order function fix, which computes an attractive fixed point of an arbitrary function f :: a -> a from an initial point x. That is, a fixed point of the form fᴷ(x) for a given f and x.
-- CONTRACT
fix :: Eq a => (a -> a) -> a -> a
-- DEFINITION [TODO: Implement fix]
fix f x = ?
My current attempt is:
fix f x | f x == x = x
| otherwise = fix f x
where x = f x
Note: Your
function will not terminate if the function does not converge from the starting
point.
can someone help me please ? I tried but it didn't return anything
A common misconception is that when you write x = ..., you assign a value in Haskell. In Haskell one does not assign a value, one declares one.
This thus means that basically you constructed a variable x in the where clause that is not the x in the head of the function, so something like:
fix :: Eq a => (a -> a) -> a -> a
fix f _ | f x == x = x
| otherwise = fix f x
where x = f x
Here you thus defined x in terms of itself: x = f x, so that means if Haskell aims to evaluate that, it will start calculating f(f(f(f(f(f(...)))))), but without any checks if the fixed point has been reached.
The solution is thus to introduce a new variable, for example x2, and thus use this like:
fix :: Eq a => (a -> a) -> a -> a
fix f x | x == x2 = x
| otherwise = fix f x2
where x2 = f x
So here x2 is the next x. Given x == x2, we return x (or x2), if not, we calculate the fixed point of f and x2, so we advanced one step in the "Quest for the fixed point".
Give a different name to the next step of iteration, like this:
where x' = f x
(instead of where x = f x). Now review the rest of your existing code, and for each occurrence of x, ask yourself: did I mean x here, or x'?
You already have answers on how to writefix from scratch. If you'd like to try it using some standard Haskell functions, I suggest you look at the function until.
until :: (a -> Bool) -> (a -> a) -> a -> a
Note the type of until is rather similar to the one you want. It just takes one extra argument of the form a -> Bool. The expression until p f x iteratively applies f starting with the initial point x, until some condition p is satisfied. And you should easily be able to write fix in the form,
fix = until p
for some function p :: a -> Bool. Now you just need to implement this stopping condition p, which checks if a point y you've calculated is a fixed point of f, that is if f y == y.
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.
I'm just getting started with Haskell. I'm trying to create a function that imitates the standard replicate function in Haskell, but using recursion. For example,
Prelude> replicate 3 "Ha!"
["Ha!","Ha!","Ha!"]
It should be of type Int -> a -> [a]. So far I have:
myReplicate :: Int -> a -> [a]
myReplicate x y = y : myReplicate (x-1) y
myReplicate 0 y = [ ]
However, my function always generates infinite lists:
Prelude> myReplicate 3 "Ha!"
["Ha!","Ha!","Ha!","Ha!","Ha!","Ha!","Ha!",...
You have to put the second case before the first, else it will never get to the second case.
myReplicate :: Int -> a -> [a]
myReplicate 0 y = [ ]
myReplicate x y = y : myReplicate (x-1) y
Your code should generate a warning reading (in GHC, at least):
Pattern match(es) are overlapped
In an equation for 'myReplicate': myReplicate 0 y = ...
What is happening is that the code tries to match your input against each definition you've written, in the order you've written (top-down). When you write f x = ..., the x variable will always match with any value of the type it represents. If all the bindings in the definition match, then that definition will be used.
In your case, the first definition is myReplicate x y = y : myReplicate (x-1) y. As I said, x and y will match with any value you pass, including 0 for the x binding. The solution proposed by #Alec shows how you can avoid this problem, by having the most specific pattern written first, and the catch-all pattern written last.
Another solution is using guards:
myReplicate :: Int -> a -> [a]
myReplicate x y
| x > 0 = y : myReplicate (x-1) y
| x == 0 = []
| otherwise = [] -- or throw an exception, or use Maybe
This way you can write the expressions to be used in any order, if you write the conditions properly (in another words, if the conditions are mutually exclusive). Note the conditions will still be evaluated first from the top, then going down until a condition is true, pretty much like an if ... else if ... else if ... else ... chain in an imperative language.
You can use map:
myReplicate :: Int -> a -> [a]
myReplicate n x = map (const x) [1..n]
You can also use $> from Data.Functor:
import Data.Functor
myReplicate :: Int -> a -> [a]
myReplicate n x = [1..n] $> x
I am very new to Haskell, and struggling a bit with a function here. The premise is simple enough: Run through a list, and combine each 3 items next to each other with another function and return a list with the results. The problem is to do it in a nice way.
Here is what I've got:
foo :: [Int] -> [Int]
foo xs
| length xs < 3 = []
| otherwise = n : foo (tail xs)
where n = calc (xs!!0) (xs!!1) (xs!!2)
-- This function is actually significantly more complicated.
calc :: Int -> Int -> Int -> Int
calc x y z = x + y - (z * 2)
-- And we can use it like this:
foo [1,2,3] -- [-3]
foo [1,2,3,4] -- [-3,-3]
foo [1,1,5,3,3] -- [-8,0,2]
What I don't like, is the 5th line, containing all the !!'s. It feels like I'm thinking about it the wrong way, and that there should be a better way of doing this. I'd like to do something like
foo (x:y:z:xs)
-- ...
But that will fail when the list gets less than three items. So, then I'd have to declare other patterns for when the list has fewer items?
Also, in case there is already a function that does what foo does (there probably is, it seems there is one for everything), then I'm not really all that interested in it. I'm trying to grok the Haskell way of doing things, more than expanding my repetoire of functions.
Edit: In JS, I'd do something like n = calc.apply(null, take(3, xs)). I wonder if Haskell has something like apply that takes an array and applies it to a function as parameters.
Edit 2 -- Solution: (based on comment below)
foo (x:y:z:xs) = calc x y z : foo (y:z:xs)
foo _ = []
Last pattern match is a catch-all, so if the first "fails" it will fall through and just return an empty list.
Well, foo (x:y:z:xs) plus a “too short clause” certainly wouldn't be a bad solution. Another would be
foo xs = case splitAt 3 xs of
([x,y,z],xs') -> calc x y z : foo (y:z:xs')
_ -> []
Or, perhaps nicest,
import Data.List (tails)
foo xs = [ calc x y z | (x:y:z:_) <- tails xs ]