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 Ropes 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(
//   """@꒸㧩첑䬜儍̀艅⸍갳읦㶄灣뜩ෳ쀏垸隰㞥䪺㟠儶㜧⏏㭻ᕦස㷯庑狨အ胡祉䍅⡱魼脳㻴毹嚋䓫ύ↡䪝ೳ㌳๢ᜰ畋㪞Ẵ㕏㋒
// """,
//   """@츳뚟뀏旹퐷ⴞæÛ㧮趍탒蜖撚眫쬏ﲔ৷랐ᅰ㒡뚙ﭷ។銬侀찎셃ꐉ쿄ꛯᖼ⦙嚮鞋甤䦛⧷䦑妺墨
// """,
//   """@欐퐷뭂륭៶嬹׋콪ᓟು㷄⺒羂⒢鋽‰ད聩惊蛪畱褅♪떧畟秄겓
// """,
//   """@蠫࿼‥᪻Ὄጢ靡ꟃ㾾᪉㐏톧峐᝟叉⅂朾蓒픬뫭ヅ☫鰎ㅖ錣븮簐졲楐邡榲භ뗦惴ک▸깇傮䧐Ḥ偫鬦泄읝묋霨넔㸧Ꝍ义籀
// """,
//   """@銗쑢턥⃃窯蒲ᒴ漮낛馅ꂖր鳃䵁痁㻅腫ຎⲳ뙤괶菼쟙渐鯔闬姼훏腪䢩炼˼ꚑ뽈
// """
// )