0

I just started to learn Haskell three days ago, aiming for a interpreter for some custom-ed semantics in Haskell. I have the Racket implementation of the interpreter, the match matching on the S-Expression in Racket is pretty handy. When it comes to Haskell, I am not quite sure whether there is something similar exists? or I have to write some data types and parse the S-Expressions to the data types defined and then use some matching mechanism in Haskell?

The thing I want to match (in racket), for example, if there is an input (from a file or stand input) like: (lambda (v1 v2) (+ v1 v2)), then in Racket, I can write the pattern like: (lambda (,v ...) ,body). and then do what I want later on. In Haskell, can I do something similar?

  • Not exactly sure what you are asking. More details please? Maybe some "wishful thinking" syntax for what you want? – luqui Jun 06 '11 at 05:40
  • Haskell isn't written in S-expressions like Racket is. What do you mean? Are you just asking whether Haskell has pattern-matching? Because it's hard to imagine you would have seen any Haskell and not seen pattern-matching. – Chuck Jun 06 '11 at 05:49
  • 4
    In Haskell you would use algebraic datatypes rather than s-expressions. They allow recursive definitions, so you can still define data as trees and they support pattern matching. You can match more than one level deep if you need to, but this often leads to ugly code. – stephen tetley Jun 06 '11 at 08:07
  • @Stephen I see your point. and the Haskell pattern matching this way is definitely not as neat as that of Racket~~~ –  Jun 06 '11 at 22:16

1 Answers1

1

Classic Haskell doesn't provide generalized pattern matching. It does provide both standard pattern matching, and guards. So you can write things like

foo :: [Int] -> ...
foo [1,2,3] = <some expression>
foo [1,2,x] = <some expression that can use x>
foo (x:xs) = <some expression where x is the first element, and xs is the rest>
foo (x:x':xs) = <some expression where x is the first element, x' the second, and xs is the rest>

bar :: (Int,String) -> ...
bar (1,"hello") =
bar (someInt,someString) =
bar (someInt,_) = 
bar _ = 

alternately:

bar :: (Int, String) -> ...
bar x = case x of
         (1,"hello") -> ...
         _ -> ...

alternately:

bar :: (Int, String) -> ...
bar (someInt,someString) 
         | someInt == 1 && someString == "hello" = ...
         | someInt == 2 && someString == "hello" = ...
         | otherwise = ...

GHC also provides extensions to integrate guards and pattern matching more seamlessly. See the sections on "View Patterns" and "Pattern Guards": http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html

sclv
  • 38,665
  • 7
  • 99
  • 204