-
-
Save bkyrlach/8a649ea9dcd74aa9db62 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//module M1 | |
object M1 { | |
//Next two imports are like importing Parsec | |
import scala.util.parsing.combinator.{Parsers,RegexParsers} | |
import scala.util.parsing.input._ | |
//Scalas version requires a bit more noise | |
object LispParser extends Parsers { | |
//Have to tell it that we want to parse characters | |
type Elem = Char | |
//Parsec does this much more elegantly | |
val digit: Parser[Elem] = elem('0') | elem('1') | elem('2') | | |
elem('3') | elem('4') | elem('5') | elem('6') | | |
elem('7') | elem('8') | elem('9') | |
//Haskell does this much more elegantly | |
val number: Parser[Int] = (digit*) ^^ (digits => digits.foldLeft("")((a, b) => a + b.toString).toInt) | |
//This combines everything. | |
def expression = for( | |
//In Haskell, we don't need to even worry about this result. | |
//In Scala, OTOH, we have to care, but we can immediately throw it away | |
_ <- '('; | |
_ <- '+'; | |
_ <- ' '; | |
x <- number; | |
_ <- ' '; | |
y <- number; | |
_ <- ')') | |
yield {x + y} | |
} | |
//Scala requires more cruft here | |
//Also note the lack of the 'IO' box. In Scala, we're allowed to be bad | |
//and just do side effects anywhere. Haskell does a better job here. | |
def main(args: Array[String]): Unit = { | |
//Haskells parsec is smarter about getting input as well. | |
//Here, we have to construct an object to help Scala parse our string | |
println(LispParser.expression(new CharSequenceReader("(+ 12 18)"))) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment