• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Alpha_ProgDes

Pattern matching. What is it used for?

12 posts in this topic

I know this is a complicated subject, but I'm such a beginner in it. However, my question is pretty straightforward: When or why would I use pattern-matching? In what sort of program or problem would it be useful? Does anyone have an example (of code) to demonstrate its use (in any language)?
0

Share this post


Link to post
Share on other sites
Pattern matching is an overloaded term. Do you mean pattern matching the language feature, as found in Haskell or Scala, used to break data structures apart? If so, it is useful for pulling apart a structured entity in a syntactically clean way that resembles (sometimes exactly matches) the syntax used to create the entity.

Haskell in particular uses this technique very effectively almost everywhere. A quick google for Haskell Pattern Matching will give excellent examples. Here's one from the wikibook:
dropThree ([x,y,z] ++ xs) = xs
This defines a function that drops the first three items from a list. It takes one argument, the list, which it matches to the pattern of three list items [x,y,z] concatenated with the rest of a list xs. It returns (is equal to in Haskell syntax) xs. So in effect, you use the syntax to create a list with three items prepended to pull three items off instead by putting the syntax in the argument field. Very cool!

Is there a particular language you are looking at that caused you to ask? The particulars vary.
2

Share this post


Link to post
Share on other sites
In addition to Koobs' answer, it's often used as an inline branching mechanism in functional languages where you would've used switch statements (or a pile of if/else blocks) in imperative languages. Since functional languages often use more list/tuple manipulation and stuff like Maybe/Nothing the scenario arises more often there.

[edit: so the Maybe/Nothing stuff (and even the tuples) are properly called Algebraic Data Types. The common example is working with a tree:
[code]
match node with
| Leaf x -> // do stuff with x
| Branch left right ->
// recurse left
// recurse right
[/code]
]
1

Share this post


Link to post
Share on other sites
[quote name='Koobs' timestamp='1327305925' post='4905368']
Pattern matching is an overloaded term. Do you mean pattern matching the language feature, as found in Haskell or Scala, used to break data structures apart? If so, it is useful for pulling apart a structured entity in a syntactically clean way that resembles (sometimes exactly matches) the syntax used to create the entity.

Haskell in particular uses this technique very effectively almost everywhere. A quick google for Haskell Pattern Matching will give excellent examples. Here's one from the wikibook:
dropThree ([x,y,z] ++ xs) = xs
This defines a function that drops the first three items from a list. It takes one argument, the list, which it matches to the pattern of three list items [x,y,z] concatenated with the rest of a list xs. It returns (is equal to in Haskell syntax) xs. So in effect, you use the syntax to create a list with three items prepended to pull three items off instead by putting the syntax in the argument field. Very cool!

Is there a particular language you are looking at that caused you to ask? The particulars vary.
[/quote]

Well I'm using Scheme and I know it has some pattern matching and Haskell and O'Caml have it in their languages as well.
0

Share this post


Link to post
Share on other sites
I don't know Scheme, but it looks like it has pattern matching comparable to Haskell (less pretty, IMHO, since you have to use an explicit 'match' form). Telastyn and I summed it up pretty well. It allows branching and destructuring on values. [url="http://docs.racket-lang.org/reference/match.html"]http://docs.racket-l...ence/match.html[/url] has some good examples of what [s]PLT Scheme[/s] Racket can do with matching, but I imagine you already read the examples and want to know about real-world stuff. Worth noting, though, is the sheer number of things you can match on, including regexs!

In Haskell (which is the language I have most pattern matching experience in), you can pattern match in a lot of places implicitly so you end up using it often. I often break tuple data apart into useful names instead of using fst, snd, and the like. If I have data that can be one of several forms (online examples usually mention expressions for parsers), I would use the branching feature in place of a switch or cond. I also break the data into useful names rather than using named fields.

Contrived example in messy psuedocode: Say you had a network protocol with a message type like
[CODE]
Message = Move Int,Int or Login String or Logout or Say String,String

[/CODE]
I would write the function
[CODE]
def Handle(Message)
Move X, Y: <move the character by X and Y>
Login Name: print 'Hello, ' + Name
Logout: print 'Bye!'
Say Name, Text: print Name + " says " + Text
[/CODE]

Is this helpful?
1

Share this post


Link to post
Share on other sites
C++ template specialization is a crude form of pattern matching. For better or worse, it's what allows a wide variety of compile-time meta-programming techniques.
0

Share this post


Link to post
Share on other sites
Pattern matching is the functional way of doing things, it's in a sense orthogonal to the OO-way. Given code which you may not alter, OO does allow you to define extra subclasses (for which you need to implement the necessary abstract methods, etc.), but you cannot add new methods to an existing class hierarchy "from the outside". The functional way allows you to define new functions on an existing data type, but you cannot add extra "subtypes" as you can in OO (you would have to change the data types definition, and add the extra cases to all other functions operating on it.) Common Lisp is an example of a language which allows you to work in both dimensions: you can add a new subtype, and update (without having to modify existing code) all existing function/method definitions so that they know how to operate on the new subtype.

Pattern matching also has the advantage that you can use nested patterns. An example (possibly full of bugs)

[CODE]
data Formula = Var Char
| Or Formula Formula
| And Formula Formula
| ForAll Char Formula
| Exists Char Formula
| Implies Formula Formula
| Not Formula
deriving (Show)


normalize :: Formula -> Formula
-------------------------------
normalize (Not (Exists x f)) = normalize $ ForAll x $ Not f
normalize (Not (ForAll x f)) = normalize $ Exists x $ Not f
normalize (Not (Or f f')) = normalize $ And (Not f) (Not f')
normalize (Not (And f f')) = normalize $ Or (Not f) (Not f')
normalize (Not (Not f)) = normalize f
normalize (Or (And f f') f'') = normalize $ And (Or f f'') (Or f' f'')
normalize (Or f (And f' f'')) = normalize $ And (Or f f') (Or f f'')
normalize (Implies f f') = normalize $ Or (Not f) f'
normalize (And f f') = And (normalize f) (normalize f')
normalize (Or f f') = Or (normalize f) (normalize f')
normalize (Not f) = Not $ normalize f
normalize (ForAll x f) = ForAll x $ normalize f
normalize (Exists x f) = Exists x $ normalize f
normalize f@(Var _) = f
[/CODE]

Inductive types and matching on their values is also important for proving stuff, as it allows for induction hypotheses, etc. but this might be a bit out of scope.
0

Share this post


Link to post
Share on other sites
[quote name='SamLowry' timestamp='1327500122' post='4906099']
Given code which you may not alter, OO does allow you to define extra subclasses (for which you need to implement the necessary abstract methods, etc.), but you cannot add new methods to an existing class hierarchy "from the outside".
[/quote]

There's nothing about OO in and of itself that prevents this. Though the languages that served to popularise OO tend not to support features such as structural typing or pattern matching.
0

Share this post


Link to post
Share on other sites
[quote name='edd²' timestamp='1327528067' post='4906228']
[quote name='SamLowry' timestamp='1327500122' post='4906099']
Given code which you may not alter, OO does allow you to define extra subclasses (for which you need to implement the necessary abstract methods, etc.), but you cannot add new methods to an existing class hierarchy "from the outside".
[/quote]

There's nothing about OO in and of itself that prevents this. Though the languages that served to popularise OO tend not to support features such as structural typing or pattern matching.
[/quote]
Depends on your definition of OO. If you take it "whatever C++/java/C#/Eiffel implement", then there's no simple way of adding methods. But of course, in the "true" definition of OO, I'm sure no one includes "and it absolutely must be impossible to do this". Do you know of a language which supports adding methods, and performs some sort of static verification?
0

Share this post


Link to post
Share on other sites
C#'s extension methods serve this purpose though they're not strictly 'added' depending on your definition/requirements.
0

Share this post


Link to post
Share on other sites
[quote name='Telastyn' timestamp='1327586841' post='4906415']
C#'s extension methods serve this purpose though they're not strictly 'added' depending on your definition/requirements.
[/quote]
C# extension methods don't really count in my eyes: they're nothing more than syntactic sugar for static methods in a separate class. There's no dynamic dispatch going on. (But admittedly, they're still quite useful.)

Someone told me some next version of java will have some sort of extension mechanism, but based on the information I got it would still require a lot of instanceofs to operate on existing hierarchies.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0