Skip to content

Commit

Permalink
experimenting with condiional access args
Browse files Browse the repository at this point in the history
  • Loading branch information
Mat Taylor authored and Mat Taylor committed Jan 14, 2022
1 parent 9cf8447 commit d90d2bd
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 6 deletions.
7 changes: 4 additions & 3 deletions elvis.nim
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,14 @@ template `?=`*[T](l: T, r: T) = (if not(?l): l = r)
template `=?`*[T](l: T, r: T) = (if ?r: l = r)

template `?.`*[T,U](left: T, right: proc (x: T): U):U =
if ?left and ?right(left): left.right
if ?left:
let r = left.right
if ?r: r else: default(typeof(left.right))
else: default(typeof(left.right))


# alternate syntax for conditional access to boost operator precendence (https://github.com/mattaylor/elvis/issues/3)
template `.?`*(left, right: untyped): untyped =
if ?left:
if ?left:
let r = left.right
if ?r: r else: default(typeof(left.right))
else: default(typeof(left.right))
Expand Down
Binary file modified tests
Binary file not shown.
7 changes: 4 additions & 3 deletions tests.nim
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,11 @@ suite "conditional access (chained)":
test "falsy on ref": check(objNilData.?data.?val == 0)
test "truthy on ref": check(obj.?data.?val == 10)

suite "conditional mutable":
var seq = @["one"]
suite "conditional access mutable":
var seq = @["zero", "one"]
test "truthy getter": check(seq.?pop == "one")
test "falsey getter": check(seq.?pop == "")
#test "chained truthy": check(seq.?pop.?len) == 4) # fails as pop is called twice
test "falsey getter": check(seq.?pop.?len == 0)

#[
suite "conditional access with args":
Expand Down

0 comments on commit d90d2bd

Please sign in to comment.