User Tools

Site Tools


codesnippets:patternmatching

This is an old revision of the document!


Pattern matching, again

There was already some pattern matching explained, in the context of bindings here. Here we explain pattern matching in other contexts, which are:

  • function definitions
  • list comprehensions
  • do notations

Before we start with that, we provide more details about pattern matching, regarding:

  • lists
  • algebraic data types
  • tuples

Context: function definition

  • binding actual parameters (“caller perspective”) to parameters (“inner function perspective”)
  • select the structure of data, to pick cases
  • binds parameter names, to define the function itself
  • example:
    • code:
      import Prelude hiding (length)
       
      main :: IO ()
      main = 
          do
              print (length s)                            -- "caller perspective" for first parameter of function length
       
      s :: String
      s = ('H':'e':['l', 'l', 'o']) ++ (' ':"World!")
       
      length :: [a] -> Integer
      length [] = 0                                       -- "inner function perspective" - selected when list is empty
      length (_:lrx) = 1 + (length lrx)                   -- "inner function perspective" - selected when at least one element
                                                            -- using the rest (lrx) for recursive call of length (again "caller perspective")
This website uses cookies. By using the website, you agree with storing cookies on your computer. Also you acknowledge that you have read and understand our Privacy Policy. If you do not agree leave the website.More information about cookies
You could leave a comment if you were logged in.
codesnippets/patternmatching.1618395237.txt.gz · Last modified: (external edit)

Except where otherwise noted, content on this wiki is licensed under the following license: CC0 1.0 Universal
CC0 1.0 Universal Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki