Skip to content

Instantly share code, notes, and snippets.

@honewatson
Last active April 24, 2018 02:34
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 honewatson/6631a96a10996ec9aea72de0fd881729 to your computer and use it in GitHub Desktop.
Save honewatson/6631a96a10996ec9aea72de0fd881729 to your computer and use it in GitHub Desktop.
Nim Pattern Matching Example
#chokidar "*.nim" -c "nim js -r test.nim"
import patty
import jsconsole
import jsffi
import zero_functional
import templates
type
Html* = object
title*: cstring
body*: cstring
Markdown* = object
body*: cstring
variant Content:
HtmlKind(html: Html)
MarkdownKind(markdown: Markdown)
proc htmlTemplate(html: Html): cstring = tmpli html"""
<h1>$(html.title)</h1>
<p>$(html.body)</p>
"""
proc markdownTemplate(markdown: Markdown): cstring =
# lets pretend it converts markdown
return markdown.body
proc render(content: Content): cstring =
match content:
HtmlKind(html: html):
result = htmlTemplate(html)
MarkdownKind(markdown: markdown):
result = markdownTemplate(markdown)
proc renderAll(contents: seq[Content]): cstring =
return contents --> fold("".cstring, a & render(it))
var html: Content = HtmlKind(Html(title: "Hi there", body: "My body"))
var markdown: Content = MarkdownKind(Markdown(body: "# title"))
console.log(renderAll(@[html, markdown]))
# <h1>Hi there</h1>
# <p>My body</p>
# # title
import patty
type
Dupes = enum
Bro, Bros, Bra
Beau {.acyclic.} = object
case kind: Dupes
of Bro, Bra:
tada: string
of Bros:
bada: string
bros: seq[Beau]
lala: string
proc show(x: Beau): void =
match x:
Bro(tada: tada, lala: lala):
echo tada, " ", lala, " bro"
Bra(tada: tada):
echo tada, " bra"
Bros(bada: bada, bros: bros):
echo bada, " man"
for bro in bros:
show(bro)
var xy = Beau(kind: Bro, tada: "Yes", lala: "haha")
show(xy)
show(Beau(kind: Bra, tada: "yo"))
show(Beau(kind: Bros, bada: "yoyo", bros: @[xy]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment