Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have an if function use pattern matching in Haskell?

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?

like image 998
s4342re41 Avatar asked Mar 07 '23 13:03

s4342re41


2 Answers

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
like image 125
Thomas M. DuBuisson Avatar answered Apr 30 '23 09:04

Thomas M. DuBuisson


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.

like image 42
amalloy Avatar answered Apr 30 '23 10:04

amalloy