I know that a method that takes a list input can use pattern matching like so:
testingMethod [] = "Blank"
testingMethod (x:xs) = show x
My question is, can I do this with an if function? For example, if I have a function1 that needs to check the pattern of the output from function2, how would I go about doing this? I am looking for something like this:
if (function2 inputInt == pattern((x:xs), [1,2,3])) then
Is this possible to do in haskell?
The syntax you are looking for is that of a case statement or a guard:
You said:
if (function2 inputInt == pattern((x:xs), [1,2,3])) then
In Haskell:
testingMethod inputInt | (x:xs, [1,2,3]) <- function2 inputInt = expr
| otherwise = expr2
Or using case
and let
(or you could inline things or use where
):
testingMethod inputInt =
let res = function2 inputInt
in case res of
(x:xs, [1,2,3]) -> expr
_ -> expr2
Or using view patterns:
{-# LANGUAGE ViewPatterns #-}
testingMethod (function2 -> (x:xs,[1,2,3])) = expr
testingMethod _ = expr2
Pattern matching in a function definition is simply syntactic sugar for the "fundamental" pattern matching provided by case
. For example, let's desugar your first function:
testingMethod [] = "Blank"
testingMethod (x:xs) = show x
Can be rewritten to:
testingMethod arg = case arg of
[] -> "Blank"
(x:xs) -> show x
It's not so clear what you intend your second snippet to do, so I can't really show you how it would look with a case
expression. But one possible interpretation would be something like this:
case function2 inputInt of
((x:xs), [1,2,3]) -> -- ...
(_, _) -> -- ...
This supposes that your function2
returns a tuple of two lists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With