Commit b2781d8ac3bd677de85db2aaa76ba50d7871cd5c

Thomas de Grivel 2024-11-26T18:35:26

list_each -> List.each = cfn

diff --git a/lib/kc3/0.1/list.kc3 b/lib/kc3/0.1/list.kc3
index 76850a5..057c15b 100644
--- a/lib/kc3/0.1/list.kc3
+++ b/lib/kc3/0.1/list.kc3
@@ -4,12 +4,9 @@ defmodule List do
 
   def cast = cfn List "list_init_cast" (Result, Sym, Tag)
 
-  def each = fn {
-    ([], _) { :ok }
-    ([a | b], f) { f(a); each(b, f) }
-  }
+  def each = cfn Bool "list_each" (List, Callable, Result)
 
-  def filter = cfn List "list_filter" (List, Fn, Result)
+  def filter = cfn List "list_filter" (List, Callable, Result)
 
   def find_if = fn {
     ([], _) { false }
diff --git a/libkc3/list.c b/libkc3/list.c
index 9ebac71..900c0d5 100644
--- a/libkc3/list.c
+++ b/libkc3/list.c
@@ -97,6 +97,31 @@ void list_delete_all (s_list *list)
     list = list_delete(list);
 }
 
+bool * list_each (s_list **list, p_callable *function, bool *dest)
+{
+  s_list *arg;
+  s_list *l;
+  s_tag tmp;
+  if (! (arg = list_new(NULL)))
+    return NULL;
+  l = *list;
+  while (l) {
+    if (! tag_copy(&arg->tag, &l->tag))
+      goto ko;
+    if (! eval_callable_call(*function, arg, &tmp))
+      goto ko;
+    tag_clean(&tmp);
+    l = list_next(l);
+  }
+  list_delete_all(arg);
+  *dest = true;
+  return dest;
+ ko:
+  tag_clean(&tmp);
+  list_delete_all(arg);
+  return NULL;
+}
+
 void list_f_clean (s_list **list)
 {
   s_list *l;
diff --git a/libkc3/list.h b/libkc3/list.h
index 7ad57f0..ca55e0b 100644
--- a/libkc3/list.h
+++ b/libkc3/list.h
@@ -63,6 +63,7 @@ s_list ** list_tail (s_list **list);
 s_tuple * list_to_tuple_reverse (const s_list *list, s_tuple *dest);
 
 /* Operators */
+bool *    list_each (s_list **list, p_callable *function, bool *dest);
 s_list ** list_filter (s_list **list, p_callable *function,
                        s_list **dest);
 s_list ** list_map (s_list **list, p_callable *function, s_list **dest);
diff --git a/test/ikc3/list.kc3 b/test/ikc3/list.kc3
index cbe6518..130085e 100644
--- a/test/ikc3/list.kc3
+++ b/test/ikc3/list.kc3
@@ -40,17 +40,15 @@
      ## comment 8b
   ]  ## comment 9
      ## comment 9b
-
 quote List.map([1, 2, 3, 4], fn (x) { x * 2 })
 List.map([1, 2, 3, 4], fn (x) { x * 2 })
-
 quote List.reverse([1, 2, 3, 4])
 List.reverse([1, 2, 3, 4])
-
 quote List.has?([:read], :read)
 List.has?([:read], :read)
-
 quote List.has?([:read], :write)
 List.has?([:read], :write)
 quote List.join(["1", "2", "3"], ", ")
 List.join(["1", "2", "3"], ", ")
+quote List.each([1, 2, 3], fn (x) { puts(x) })
+List.each([1, 2, 3], fn (x) { puts(x) })
diff --git a/test/ikc3/list.out.expected b/test/ikc3/list.out.expected
index 62f7c09..61273c4 100644
--- a/test/ikc3/list.out.expected
+++ b/test/ikc3/list.out.expected
@@ -30,3 +30,8 @@ List.has?([:read], :write)
 false
 List.join(["1", "2", "3"], ", ")
 "1, 2, 3"
+List.each([1, 2, 3], fn (x) { puts(x) })
+1
+2
+3
+true