开发者

Can Haskell match on S-Expression like match of Racket?

开发者 https://www.devze.com 2023-03-11 11:33 出处:网络
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-Expre

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 m开发者_如何学Pythonatching 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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消