Pattern matching against Just containing a pair - haskell

I'm experimenting with Haskell and I'm wondering why I couldn't match against a Just containing a pair. I have little experience with this language and I'm completely lost.
f :: Int -> Maybe (Int, [Int])
f 100 = Nothing
f x = Just (x,[x])
g :: Int -> Maybe Int
g x
| u==Nothing = Nothing
| u==(Just (r,s)) = Just r
where
u=f x
So what is wrong with this code. GHC says that r and s are not in scope.

If you want to pattern match in a guard, you have to use a pattern guard:
g :: Int -> Maybe Int
g x
| Just (r,_) <- u = Just r
| otherwise = Nothing
where
u = f x
After all, (==) is a regular function, you need values on both sides to use it. Since r and s aren't known in u == Just (r,s), the compiler gives you your error message.
By the way, taking a Maybe and return Nothing if the value was Nothing or Just (h x) for a function h and Just x is so common, it forms a pattern: fmap. You can write
g :: Int -> Maybe Int
g x = fmap fst (f x)

Because the guard expression can't do pattern matching.
Guard expression is just like a boolean expression, it can't do binding. It just uses the binding before |, in this case x.
So working solution will be like this.
g :: Int -> Maybe Int
g x = case f x of
Nothing -> Nothing
Just (r,_) -> Just r

You can use case expressions
g :: Int -> Maybe Int
g x =
case f x of
Nothing -> Nothing
Just (r,s) -> Just r

Related

How to write a fixed point function in haskell

I have a function with the following signature:
simCon :: [Constraint] -> Maybe [Constraint]
I would like to write a method which, incase simCon returns Just [Constraint], I want to feed them back into simCon and rerun the method, and to keep doing this until the input is the same as the output.
In case of Nothing, I would want to terminate the algorithm.
I have something that would work if both the input and output are the same type
fixed :: Eq a => (a -> a) -> a -> a
fixed f a
| a == a' = a
| otherwise = fixed f a'
where a' = f a
But this isn't going to work because I return a Maybe now. Can someone suggest a way to write a similar function but for a return type of Maybe?
We can make use of the bind function here:
import Data.Bool(bool)
import Control.Monad(liftM2)
fixedM :: (Eq a, Monad m) => (a -> m a) -> a -> m a
fixedM f = go
where go x = f x >>= (liftM2 bool go pure <*> (x ==))
A more verbose implementation is:
fixedM :: (Eq a, Monad m) => (a -> m a) -> a -> m a
fixedM f x = do
x' <- f x
if x == x'
then pure x'
else fixedM f x'
We thus first calculate x' with f x. In case f x return Just x', then we continue. In case f x return Nothing, the fixedM will return Nothing as well. We then compare x with x'. In case the two are equal, we return pure x', otherwise we recurse on fixedM f x'.
Alternatively, we can make use of pattern matching, although this is basically making the bind operator explicit (and only working for a Maybe):
import Control.Monad(ap)
fixedM :: Eq a => (a -> Maybe a) -> a -> Maybe a
fixedM f = ap go f
where go x (Just x') | x == x' = go x' (f x')
| otherwise = Just x'
go _ _ = Nothing
we can make it more compact by using pattern guards:
fixedM :: Eq a => (a -> Maybe a) -> a -> Maybe a
fixedM f = go
where go x | Just x' <- f x = bool (go x) (Just x) (x == x')
| otherwise = Nothing

Haskell - fast naming of projection functions

Suppose I want to define a function f in terms of some other predefined function g as follows:
f :: Int -> Int -> Int
f 2 b = g b
f _ _ = 1
That is, I want to define the projection, f(2,_) : Int->Int to be the same as g(_) : Int->Int. Gladly, Haskell has first class functions, and so definitions like the following squarePlusOne are valid and standard:
plusOne :: Int -> Int
plusOne i = i+1
square :: Int -> Int
square i = i*i
squarePlusOne :: Int -> Int
squarePlusOne = plusOne . Square
With Haskell's currying (ie. f takes just one Int as input and returns an (Int->Int) typed function), I am surprised I cannot write
f 2 = g
Why not? Or is there some other syntax?
Indeed, writing f 2 = g is a valid way to define f. However, when defining functions in this way, remember you must define the whole function with the same pattern signature. That is, you may not exhaust your function by writing
f 2 = g
f i j = i+j
Instead, this may be achieved like so:
f 2 = g
f i = (\j-> i+j)
You can use the const function, which creates a function that ignores its argument to return a fixed value.
f :: Int -> Int -> Int
f 2 = g -- f 2 x = g x
f _ = const 1 -- f _ x = const 1 x == (\_ -> 1) x == 1

Pattern matching for return values

I know I can use pattern matching for function parameters like this:
fn :: (Integral a) => (a,a) -> (a, a)
fn (x,y) = (y,x)
But how can I match the return value? I would expect something like this:
g :: (Integral a) => a -> a
g z = do
(x, y) = fn (z, z + 5)
x `mod` y
This results in a syntax error. Is there a way to match return values? Basically, I want to split the returned tuple into two variables.
The do is used a syntactical sugar for monads. Your function is however not a monad.
What you can do is use a let-clause, like:
g :: (Integral a) => a -> a
g z = let (x,y) = fn (z,(z+5)) in x `mod` y
Or a where-clause:
g :: (Integral a) => a -> a
g z = x `mod` y
where (x,y) = fn (z,(z+5))
You can also define a pattern in a lambda-expression, like:
g :: (Integral a) => a -> a
g z = (\(x,y) -> x `mod` y) $ fn (z,(z+5))
Along these lines, you can also define a helper function that does the pattern matching, like:
g :: (Integral a) => a -> a
g z = h $ fn (z,(z+5))
where h (x,y) = x `mod` y
This can be useful if there are several patterns that need to be handled differently (like the Nothing and Just x for the Maybe a type).
Say for instance that you defined a function:
foo :: Int -> Int -> Maybe Int
foo x y | x > y = Just x
| otherwise = Nothing
than you can define bar with a helper function qux to handle the output of foo, like:
bar :: Int -> Int -> Int
bar x y = qux $ foo x y
where qux Nothing = y
qux (Just z) = z
Finally in the case of 2-tuples, you can decide not to use pattern matching, but use fst :: (a,b) -> a and snd :: (a,b) -> b, like for instance:
g :: (Integral a) => a -> a
g z = let t = fn (z,(z+5)) in ( fst t) `mod` (snd t)
But this is less elegant since here one has to start thinking about what fst and snd do, and furtermore if not optimized, it can result in additional computation overhead.
Which one to pick depends of course on the context and a bit on personal taste. Since here the pattern is the only one, I would pick the let or where pattern, but like the French say: "Les goûts et les couleurs ne se discutent pas.".
My personal preference in the general case, is to use a case .. of expression. For instance, if f :: Int -> Maybe Int, we can write
g :: Int -> Int
g x = case f x of
Nothing -> 5
Just y -> x+y
For types with only one constructor, like tuples, then let .. in can also be used:
h a = let (x, y) = foo a in ...
Remember, however, that case is strict while let is lazy. E.g.
case undefined of (x,y) -> 5
raises an error. Instead
let (x, y) = undefined in 5
evaluates to 5. So, they are not completely equivalent. They became such when using irrefutable patterns, or matching against a newtype constructor.

Haskell pattern match on content of list

I have a list of elements:
data Foo = A Int | B Int | C Int
myList :: [Foo]
myList = [A 1, B 2, C 3]
I want a function that gets the value of a specific constructor, if existing:
-- returns value of the first A constructor, if exists:
getA :: [Foo] -> Maybe Int
-- returns value of the first B constructor, if exists:
getB :: [Foo] -> Maybe Int
Any elegant solution?
And what about a getX function, capable of getting the value of any specified constructor in the list?
This will work
getA theList = listToMaybe [x | A x <- theList]
getB theList = listToMaybe [x | B x <- theList]
You will need to import Data.Maybe.
Generalizing this would be possible, but tricky.... What type would you even want this function to have? ([a]->somethingToRepresentAConstructor->Int).
And what about a getX function, capable of getting the value of any specified constructor in the list?
Regarding the generalization, the somethingToRepresentAConstructor could be a String?
You can generalize a bit more and get
firstJust :: (a -> Maybe b) -> [a] -> Maybe b
firstJust f xs = case filter isJust (map f xs) of
x : _ -> x
[] -> Nothing
getA = firstJust f
where f (A x) = Just x
f _ = Nothing
getB = firstJust f
where f (B x) = Just x
f _ = Nothing

Writing in pointfree style f x = g x x

I am learning Haskell. I'm sorry for asking a very basic question but I cant seem to find the answer. I have a function f defined by :
f x = g x x
where g is an already defined function of 2 arguments. How do I write this pointfree style?
Edit : without using a lambda expression.
Thanks
f can be written with Control.Monad.join:
f = join g
join on the function monad is one of the primitives used when constructing point-free expressions, as it cannot be defined in a point-free style itself (its SKI calculus equivalent, SII — ap id id in Haskell — doesn't type).
This is known as "W" combinator:
import Control.Monad
import Control.Monad.Instances
import Control.Applicative
f = join g -- = Wg (also, join = (id =<<))
= (g `ap` id) -- \x -> g x (id x) = SgI
= (<*> id) g -- = CSIg
= g =<< id -- \x -> g (id x) x
= id =<< g -- \x -> id (g x) x
S,K,I are one basic set of combinators; B,C,K,W are another - you've got to stop somewhere (re: your "no lambda expression" comment):
_B = (.) -- _B f g x = f (g x) = S(KS)K
_C = flip -- _C f x y = f y x = S(S(K(S(KS)K))S)(KK)
_K = const -- _K x y = x
_W = join -- _W f x = f x x = CSI = SS(KI) = SS(SK)
_S = ap -- _S f g x = f x (g x) = B(B(BW)C)(BB) = B(BW)(BBC)
= (<*>) -- from Control.Applicative
_I = id -- _I x = x = WK = SKK = SKS = SK(...)
{-
Wgx = gxx
= SgIx = CSIgx
= Sg(KIg)x = SS(KI)gx
= gx(Kx(gx)) = gx(SKgx) = Sg(SKg)x = SS(SK)gx
-- _W (,) 5 = (5,5)
-- _S _I _I x = x x = _omega x -- self-application, untypeable
-}
I got here by pure chance, and I want to offer my solution, as nobody has mentioned lifting yet in this thread, not explicitly at least.
This is a solution:
f = liftM2 g id id
How to look at it?
g has type a -> a -> b, i.e. it takes two values of some type (the same type for both, otherwise the definition the OP gave of f wouldn't make sense), and gives back another value of some type (not necessarily of the same type as the arguments);
lift2M g is the lifted version of g and it has type (Monad m) => m a -> m a -> m b: it takes two monadic values, which are each a value in a so-far-unspecified context, and gives back a monadic value;
when passing two functions to liftM2 g, the die is cast on what the context of the Monad is: it is that the values are not in there yet, but will eventually be, when the function will receive the arguments it needs; in other words, functions are monads that store their own future values; therefore, lift2M g takes in input two functions (or, the future values of two functions), and gives back the another function (or, its future value); knowing this, its type is the same as above if you change m to (->) r, or r ->: (r -> a) -> (r -> a) -> (r -> b)
the two functions that we pass are both id, which promises it'll give back the same value it receives;
liftM2 g id id is therefore a function of type r -> b that passes its argument to those two ids, which let it unchanged and forward it to g.
In a similar fashion, one can exploit that functions are applicative functors, and use this solution:
f = g <$> id <*> id

Resources