diff --git a/builtin/core.wren b/builtin/core.wren index da6e46a4..7f63a3ef 100644 --- a/builtin/core.wren +++ b/builtin/core.wren @@ -14,6 +14,13 @@ class Sequence { } return result } + + all(f) { + for (element in this) { + if (!f.call(element)) return false + } + return true + } } class List is Sequence { diff --git a/doc/site/core-library.markdown b/doc/site/core-library.markdown index 8cbcbc9d..cb99caf2 100644 --- a/doc/site/core-library.markdown +++ b/doc/site/core-library.markdown @@ -313,6 +313,10 @@ Removes all items from the list. The number of items in the list. +### **forall(predicate)** + +Tests whether all the elements in the list pass the `predicate`. + ### **insert**(item, index) **TODO** diff --git a/src/wren_core.c b/src/wren_core.c index 712019e4..9a84c6c5 100644 --- a/src/wren_core.c +++ b/src/wren_core.c @@ -57,6 +57,13 @@ static const char* libSource = " }\n" " return result\n" " }\n" +"\n" +" all(f) {\n" +" for (element in this) {\n" +" if (!f.call(element)) return false\n" +" }\n" +" return true\n" +" }\n" "}\n" "\n" "class List is Sequence {\n" diff --git a/test/list/forall.wren b/test/list/forall.wren new file mode 100644 index 00000000..c3ec24e5 --- /dev/null +++ b/test/list/forall.wren @@ -0,0 +1,9 @@ +var a = [1, 2, 3] +var b = a.all {|x| x > 1 } +IO.print(b) // expect: false + +var d = a.all {|x| x > 0 } +IO.print(d) // expect: true + +var e = [].all {|x| false } +IO.print(e) // expect: true diff --git a/test/list/forall_non_bool_returning_fn.wren b/test/list/forall_non_bool_returning_fn.wren new file mode 100644 index 00000000..b217702d --- /dev/null +++ b/test/list/forall_non_bool_returning_fn.wren @@ -0,0 +1 @@ +[1, 2, 3].all {|x| "string" } // expect runtime error: String does not implement method '!' with 0 arguments. diff --git a/test/list/forall_non_function_arg.wren b/test/list/forall_non_function_arg.wren new file mode 100644 index 00000000..cca752fc --- /dev/null +++ b/test/list/forall_non_function_arg.wren @@ -0,0 +1 @@ +[1, 2, 3].all("string") // expect runtime error: String does not implement method 'call' with 1 argument. \ No newline at end of file