Question

Please briefly explain, alongside example code, how pattern matching on parameters in function definitions is actually...

Please briefly explain, alongside example code, how pattern matching on parameters in function definitions is actually just syntactic sugar for case expressions in Haskell functional language.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Pattern matching is done in a function on the parameters to check how the execution will proceed. For example, if you want to print second element of every list, you will check for empty list, single element and second element list.

If empty return empty list, for single element also return empty list only when it has two elements call it recursively. Pattern matching is done as below

function_name (_:x:xs) = do whatever

_ represents one character, x for another character and xs for rest of the list

This is done on the parameters of the function.

In haskell language case expression checks for pattern once unlike case expression in C where every case is defined separately for particular value of the variable. switch keyword is used to math pattern in this language.

The syntax is as below.

case expression of pattern -> result  

   pattern -> result  

keywords used here are case and of

This is similar to pattern matching done above.

Working example of the two


--function with pattern matching
top :: [a] -> a
top [] = error "List is empty "
top (x:_) = x

--function with case expression
top :: [a] -> a
top xs = case xs of [] -> error "List is empty "
(x:_) -> x

main = do
--test with different test values as mentioned
putStrLn "The input is:" --display this line
let p = [1,2,3,4,5]
print(p)
putStrLn "The output is:" --display this line
print(top p )

above functions run individually with the input a list give the following output

The input is: [1,2,3,4,51 The output is:

since both perform same operation of checking patterns, pattern matching on parameters in function definitions is actually just syntactic sugar for case expressions in Haskell functional language.

Add a comment
Know the answer?
Add Answer to:
Please briefly explain, alongside example code, how pattern matching on parameters in function definitions is actually...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT