I'm changing some Haskell code from using lists to sets. I understand everything required, I think, but I'm not sure how to pattern match on sets. Lists have this nice literal syntax that seems hard to emulate with the Set constructor. For example, I might have some code like this:
foo [] = []
foo x = other_thing
How can I write this code so it uses Sets instead of lists?
(Pattern matching in Haskell is different from that found in logic programming languages such as Prolog; in particular, it can be viewed as "one-way" matching, whereas Prolog allows "two-way" matching (via unification), along with implicit backtracking in its evaluation mechanism.)
Pattern matching consists of specifying patterns to which some data should conform and then checking to see if it does and deconstructing the data according to those patterns. When defining functions, you can define separate function bodies for different patterns.
We use pattern matching in Haskell to simplify our codes by identifying specific types of expression. We can also use if-else as an alternative to pattern matching. Pattern matching can also be seen as a kind of dynamic polymorphism where, based on the parameter list, different methods can be executed.
import qualified Data.Set as Set
foo set
| Set.null set = bar
| otherwise = baz
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