Skip to content

Commit fd17f94

Browse files
committed
Added 'sqrt' and 'integer'
1 parent ea9d96d commit fd17f94

File tree

3 files changed

+44
-3
lines changed

3 files changed

+44
-3
lines changed

Sources/SLispCore/builtins/Core.swift

+24-1
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,9 @@ class Core: Builtins {
246246
throw LispError.runtime(msg: "'doc' requires the argument to be a function")
247247
}
248248

249-
print(docstring ?? "")
249+
if docstring != nil {
250+
return .string(docstring!)
251+
}
250252

251253
return .nil
252254
}
@@ -653,5 +655,26 @@ class Core: Builtins {
653655
return !x
654656
}
655657
}
658+
659+
// MARK: integer
660+
addBuiltin("integer", docstring: "") { args, parser, env throws in
661+
if args.count != 1 {
662+
throw LispError.runtime(msg: "'integer' expects 1 argument.")
663+
}
664+
665+
switch args[0] {
666+
case .number(let num):
667+
return .number(.integer(num.intValue()))
668+
case .string(let str):
669+
let v = Int(str)
670+
if v != nil {
671+
return .number(.integer(v!))
672+
} else {
673+
return .nil
674+
}
675+
default:
676+
throw LispError.runtime(msg: "'integer' expects a number or string argument.")
677+
}
678+
}
656679
}
657680
}

Sources/SLispCore/builtins/Math.swift

+13
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,19 @@ class MathBuiltins : Builtins {
7474
return .number(.integer(n))
7575
}
7676

77+
78+
addBuiltin("sqrt", docstring: "") { args, parser, env throws in
79+
if args.count != 1 {
80+
throw LispError.runtime(msg: "'sqrt' requires 1 argument")
81+
}
82+
83+
guard case let .number(n) = args[0] else {
84+
throw LispError.runtime(msg: "'sqrt' requires a number argument")
85+
}
86+
87+
return .number(.float(sqrt(n.floatValue())))
88+
}
89+
7790
return builtins
7891
}
7992
}

stdlib/test.sl

+7-2
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,16 @@
5555
(if (! x)
5656
(if (|| (empty? description) (nil? description))
5757
(throw :testAssertionError)
58-
(throw :testAssertionError (first description)))))
58+
(do
59+
(print (first description))
60+
(throw :testAssertionError (first description))))))
5961

6062
(defn assertEqual
6163
(x y & description)
62-
(apply assert (concat (== x y) description)))
64+
(let (desc (if (|| (nil? description) (empty? description))
65+
(str "Assertion failure: " x " is not equal to " y)
66+
description))
67+
(apply assert (concat (== x y) desc))))
6368

6469
(defn assertNotEqual
6570
(x y & description)

0 commit comments

Comments
 (0)