Skip to content

Instantly share code, notes, and snippets.

@tommorris
Last active November 22, 2018 21:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommorris/26a48a607b4895c607a4f76b076731ae to your computer and use it in GitHub Desktop.
Save tommorris/26a48a607b4895c607a4f76b076731ae to your computer and use it in GitHub Desktop.
A Scala implementation of tomscott's 7-segment display problem
import scala.util.matching.Regex
import scala.io.Source
val matcher: Regex = "[gkmqvwxzio]".r
def displayableOn7SegmentDisp(str: String) = matcher.findAllIn(str).isEmpty
val filename = "/Users/tom/Desktop/words_alpha.txt"
val words = Source.fromFile(filename).getLines.toStream
val longestWord = words.filter(displayableOn7SegmentDisp).sortWith(_.length > _.length).head
println(longestWord)

This is a simple Scala implementation of Tom Scott's 7 Segment Display problem that uses Scala's Streams.

The nice thing about this style of programming is you decouple the logic of processing the giant list of words from what you want to do with them. If you just wished to retrieve the first ten words from the list that are over 10 characters long, you could do that by just changing line 9. You wouldn't then have to rewrite for loops. And you give the compiler opportunities to be clever.

This is quite a useful teaching example. Scala also produces quite sensible, readable code that isn't just code-golfed to hell.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment