Section 1 - Basics
Let’s dive straight into an example.
Twitter Handles
We know that (simplistically) a Twitter handle always starts with a literal ‘@’ symbol, followed by any string. We can define that with:
import ropes.core._
type TwitterHandle = Concat[Literal['@'], AnyString]
Or you can use Concat
as an infix type:
type TwitterHandle = Literal['@'] Concat AnyString
Now, we can parse matching strings, and write them back to their original form:
Rope.parseTo[TwitterHandle]("!Bob")
// res0: Either[Rope.InvalidValue.type, TwitterHandle] = Left(
// value = InvalidValue
// )
val Right(howy) = Rope.parseTo[TwitterHandle]("@HowyP")
// howy: TwitterHandle = Concat(
// prefix = Literal(value = '@'),
// suffix = AnyString(value = "HowyP")
// )
howy.write
// res1: String = "@HowyP"
Composing and decomposing
After parsing, we can access the parts of the rope based on the
properties of each individual type. In this case, they are pretty basic.
A Concat
has a prefix and suffix, and the Literal
and AnyString
contain single values:
howy.prefix
// res2: Literal[@] = Literal(value = '@')
howy.prefix.value
// res3: Char = '@'
howy.suffix
// res4: AnyString = AnyString(value = "HowyP")
howy.suffix.value
// res5: String = "HowyP"
We can also create new handles from scratch, or modify existing ones:
val twitter: TwitterHandle = Concat(Literal('@'), AnyString("Twitter"))
// twitter: TwitterHandle = Concat(
// prefix = Literal(value = '@'),
// suffix = AnyString(value = "Twitter")
// )
val bob: TwitterHandle = howy.copy(suffix = AnyString("Bob"))
// bob: TwitterHandle = Concat(
// prefix = Literal(value = '@'),
// suffix = AnyString(value = "Bob")
// )
Generating
Lastly, a feature of all Rope
s is that they can be generated via
Scalacheck Arbitrary
:
import org.scalacheck.Arbitrary.arbitrary
import ropes.scalacheck._
List.fill(5)(arbitrary[TwitterHandle].sample).flatten.map(_.write + '\n')
// res6: List[String] = List(
// """@꒸㧩첑䬜儍̀艅⸍갳읦㶄灣뜩ෳ쀏垸隰㞥䪺㟠儶㜧⏏㭻ᕦස㷯庑狨အ胡祉䍅⡱魼脳㻴毹嚋䓫ύ↡䪝ೳ㌳ᜰ畋㪞Ẵ㕏㋒
// """,
// """@츳뚟뀏旹퐷ⴞæÛ㧮趍탒蜖撚眫쬏ﲔ৷랐ᅰ㒡뚙ﭷ។銬侀찎셃ꐉ쿄ꛯᖼ⦙嚮鞋甤䦛⧷䦑妺墨
// """,
// """@欐퐷뭂륭៶嬹콪ᓟು㷄⺒羂⒢鋽ད聩惊蛪畱褅♪떧畟秄겓
// """,
// """@蠫‥᪻Ὄጢ靡ꟃ㾾᪉㐏톧峐叉⅂朾蓒픬뫭ヅ☫鰎ㅖ錣븮簐졲楐邡榲භ뗦惴ک▸깇傮䧐Ḥ偫鬦泄읝묋霨넔㸧Ꝍ义籀
// """,
// """@銗쑢턥窯蒲ᒴ漮낛馅ꂖր鳃䵁痁㻅腫ຎⲳ뙤괶菼쟙渐鯔闬姼훏腪䢩炼˼ꚑ뽈
// """
// )