1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
------------------------------------------------------------------------
--- This module contains an implementation of set functions.
--- The general idea of set functions is described in:
---
--- > S. Antoy, M. Hanus: Set Functions for Functional Logic Programming
--- > Proc. 11th International Conference on Principles and Practice
--- > of Declarative Programming (PPDP'09), pp. 73-82, ACM Press, 2009
--- 
--- The general concept of set functions is as follows.
--- If `f` is an n-ary function, then `(setn f)` is a set-valued
--- function that collects all non-determinism caused by f (but not
--- the non-determinism caused by evaluating arguments!) in a set.
--- Thus, `(setn f a1 ... an)` returns the set of all
--- values of `(f b1 ... bn)` where `b1`,...,`bn` are values
--- of the arguments `a1`,...,`an` (i.e., the arguments are
--- evaluated "outside" this capsule so that the non-determinism
--- caused by evaluating these arguments is not captured in this capsule
--- but yields several results for `(setn...)`.
--- Similarly, logical variables occuring in `a1`,...,`an` are not bound
--- inside this capsule (in PAKCS they cause a suspension until
--- they are bound).
--- 
--- *Remark:*
--- Since there is no special syntax for set functions,
--- one has to write `(setn f)` for the set function of the
--- _n-ary top-level function_ `f`.
--- The correct usage of set functions is currently not checked by
--- the compiler, i.e., one can also write unintended uses
--- like `set0 ((+1) (1 ? 2))`.
--- In order to check the correct use of set functions,
--- it is recommended to apply the tool
--- [CurryCheck](https://cpm.curry-lang.org/pkgs/currycheck.html)
--- on Curry programs which reports illegal uses of set functions
--- (among other properties).
--- 
--- The set of values returned by a set function is represented
--- by an abstract type 'Values' on which several operations are
--- defined in this module. Actually, it is a multiset of values,
--- i.e., duplicates are not removed.
---
--- The handling of failures and nested occurrences of set functions
--- is not specified in the previous paper. Thus, a detailed description
--- of the semantics of set functions as implemented in this library
--- can be found in the paper
---
--- > J. Christiansen, M. Hanus, F. Reck, D. Seidel:
--- > A Semantics for Weakly Encapsulated Search in Functional Logic Programs
--- > Proc. 15th International Conference on Principles and Practice
--- > of Declarative Programming (PPDP'13), pp. 49-60, ACM Press, 2013
--- 
--- Note that the implementation of this library uses multisets
--- instead of sets. Thus, the result of a set function might
--- contain multiple values. From a declarative point of view,
--- this is not relevant. It has the advantage that equality
--- is not required on values, i.e., encapsulated values can also
--- be functional.
--- 
--- The PAKCS implementation of set functions has several restrictions,
--- in particular:
--- 
--- 1. The multiset of values is completely evaluated when demanded.
---    Thus, if it is infinite, its evaluation will not terminate
---    even if only some elements (e.g., for a containment test)
---    are demanded. However, for the emptiness test, at most one
---    value will be computed
--- 2. The arguments of a set function are strictly evaluated before
---    the set functions itself will be evaluated.
--- 3. If the multiset of values contains unbound variables,
---    the evaluation suspends.
---
--- @author Michael Hanus, Fabian Reck
--- @version November 2022
------------------------------------------------------------------------
{-# LANGUAGE CPP #-}
{-# OPTIONS_FRONTEND -Wno-incomplete-patterns #-}

module Control.Search.SetFunctions
  (set0, set1, set2, set3, set4, set5, set6, set7




  , Values, isEmpty, notEmpty, valueOf
  , chooseValue, choose, selectValue, select, getSomeValue, getSome
  , mapValues, foldValues, filterValues
  , minValue, minValueBy, maxValue, maxValueBy
  , values2list, printValues, sortValues, sortValuesBy
  ) where

import Data.List ( delete, minimum, minimumBy, maximum, maximumBy, sortBy )



import Control.Search.Unsafe ( allValues, oneValue )


------------------------------------------------------------------------
--- Combinator to transform a 0-ary function into a corresponding set function.
set0 :: b -> Values b








set0 f = Values (oneValue f) (allValues f)


--- Combinator to transform a unary function into a corresponding set function.
set1 :: (a1 -> b) -> a1 -> Values b








set1 f x | isVal x = Values (oneValue (f x)) (allValues (f x))


--- Combinator to transform a binary function into a corresponding set function.
set2 :: (a1 -> a2 -> b) -> a1 -> a2 -> Values b








set2 f x1 x2
  | isVal x1 & isVal x2
  = Values (oneValue (f x1 x2)) (allValues (f x1 x2))


--- Combinator to transform a function of arity 3
--- into a corresponding set function.
set3 :: (a1 -> a2 -> a3 -> b) -> a1 -> a2 -> a3 -> Values b









set3 f x1 x2 x3
  | isVal x1 & isVal x2 & isVal x3
  = Values (oneValue (f x1 x2 x3)) (allValues (f x1 x2 x3))


--- Combinator to transform a function of arity 4
--- into a corresponding set function.
set4 :: (a1 -> a2 -> a3 -> a4 -> b) -> a1 -> a2 -> a3 -> a4 -> Values b










set4 f x1 x2 x3 x4
  | isVal x1 & isVal x2 & isVal x3 & isVal x4
  = Values (oneValue (f x1 x2 x3 x4)) (allValues (f x1 x2 x3 x4))


--- Combinator to transform a function of arity 5
--- into a corresponding set function.
set5 :: (a1 -> a2 -> a3 -> a4 -> a5 -> b)
      -> a1 -> a2 -> a3 -> a4 -> a5 -> Values b










set5 f x1 x2 x3 x4 x5
  | isVal x1 & isVal x2 & isVal x3 & isVal x4 & isVal x5
  = Values (oneValue (f x1 x2 x3 x4 x5)) (allValues (f x1 x2 x3 x4 x5))


--- Combinator to transform a function of arity 6
--- into a corresponding set function.
set6 :: (a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> b)
      -> a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> Values b











set6 f x1 x2 x3 x4 x5 x6
  | isVal x1 & isVal x2 & isVal x3 & isVal x4 & isVal x5 & isVal x6
  = Values (oneValue (f x1 x2 x3 x4 x5 x6))
           (allValues (f x1 x2 x3 x4 x5 x6))


--- Combinator to transform a function of arity 7
--- into a corresponding set function.
set7 :: (a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> a7 -> b)
      -> a1 -> a2 -> a3 -> a4 -> a5 -> a6 -> a7 -> Values b











set7 f x1 x2 x3 x4 x5 x6 x7
  | isVal x1 & isVal x2 & isVal x3 & isVal x4 & isVal x5 & isVal x6 & isVal x7
  = Values (oneValue (f x1 x2 x3 x4 x5 x6 x7))
           (allValues (f x1 x2 x3 x4 x5 x6 x7))


------------------------------------------------------------------------
-- Auxiliaries:















-- Returns `True` after evaluating the argument to a ground value.
isVal :: a -> Bool
isVal x = (id $## x) `seq` True



------------------------------------------------------------------------
--- Abstract type representing multisets of values.





-- In PAKCS, values are represented as lists but the first argument
-- is used if values are tested for emptiness of a single value
-- is selected. This has the advantage that one can deal with infinite
-- search spaces as long as one is only interested in an emptiness
-- test or a single value.
data Values a = Values (Maybe a) [a]


--- Internal operation to extract all elements of a multiset of values.
valuesOf :: Values a -> [a]



valuesOf (Values _ s) = s


----------------------------------------------------------------------

--- Is a multiset of values empty?
isEmpty :: Values a -> Bool

isEmpty (Values firstval _) = case firstval of Nothing -> True
                                               Just _  -> False




--- Is a multiset of values not empty?
notEmpty :: Values a -> Bool
notEmpty vs = not (isEmpty vs)

--- Is some value an element of a multiset of values?
valueOf :: Eq a => a -> Values a -> Bool
valueOf e s = e `elem` valuesOf s

--- Chooses (non-deterministically) some value in a multiset of values
--- and returns the chosen value. For instance, the expression
---
---     chooseValue (set1 anyOf [1,2,3])
---
--- non-deterministically evaluates to the values `1`, `2`, and `3`.

--- Thus, `(set1 chooseValue)` is the identity on value sets, i.e.,
--- `(set1 chooseValue s)` contains the same elements as the
--- value set `s`.
chooseValue :: Eq a => Values a -> a
chooseValue s = fst (choose s)

--- Chooses (non-deterministically) some value in a multiset of values
--- and returns the chosen value and the remaining multiset of values.
--- Thus, if we consider the operation `chooseValue` defined by
---
---     chooseValue x = fst (choose x)
---
--- then `(set1 chooseValue)` is the identity on value sets, i.e.,
--- `(set1 chooseValue s)` contains the same elements as the
--- value set `s`.
choose :: Eq a => Values a -> (a, Values a)



choose (Values _ vs) =
  (x, Values (if null xs then Nothing else Just (head xs)) xs)

 where x  = foldr1 (?) vs
       xs = delete x vs

--- Selects (indeterministically) some value in a multiset of values
--- and returns the selected value.
--- Thus, `selectValue` has always at most one value, i.e., it is
--- a deterministic operation.
--- It fails if the value set is empty.
---
--- **NOTE:**
--- The usage of this operation is only safe (i.e., does not destroy
--- completeness) if all values in the argument set are identical.
selectValue :: Values a -> a

selectValue (Values (Just val) _) = val




--- Selects (indeterministically) some value in a multiset of values
--- and returns the selected value and the remaining multiset of values.
--- Thus, `select` has always at most one value, i.e., it is
--- a deterministic operation.
--- It fails if the value set is empty.
---
--- **NOTE:**
--- The usage of this operation is only safe (i.e., does not destroy
--- completeness) if all values in the argument set are identical.
select :: Values a -> (a, Values a)



select (Values _ (x:xs)) =
  (x, Values (if null xs then Nothing else Just (head xs)) xs)


--- Returns (indeterministically) some value in a multiset of values.
--- If the value set is empty, `Nothing` is returned.
getSomeValue :: Values a -> IO (Maybe a)




getSomeValue (Values mbval _) = return mbval


--- Selects (indeterministically) some value in a multiset of values
--- and returns the selected value and the remaining multiset of values.
--- Thus, `select` has always at most one value.
--- If the value set is empty, `Nothing` is returned.
getSome :: Values a -> IO (Maybe (a, Values a))




getSome (Values _ [])     = return Nothing
getSome (Values _ (x:xs)) =
  return (Just (x, Values (if null xs then Nothing else Just (head xs)) xs))


--- Maps a function to all elements of a multiset of values.
mapValues :: (a -> b) -> Values a -> Values b



mapValues f (Values mbval s) = Values (maybe Nothing (Just . f) mbval) (map f s)


--- Accumulates all elements of a multiset of values by applying a binary
--- operation. This is similarly to fold on lists, but the binary operation
--- must be **commutative** so that the result is independent of the order
--- of applying this operation to all elements in the multiset.
foldValues :: (a -> a -> a) -> a -> Values a -> a
foldValues f z s = foldr f z (valuesOf s)

--- Keeps all elements of a multiset of values that satisfy a predicate.
filterValues :: (a -> Bool) -> Values a -> Values a



filterValues p (Values _ s) = Values val xs
 where
  xs = filter p s
  val = if null xs then Nothing else Just (head xs)


--- Returns the minimum of a non-empty multiset of values
--- according to the given comparison function on the elements.
minValue :: Ord a => Values a -> a
minValue s = minimum (valuesOf s)

--- Returns the minimum of a non-empty multiset of values
--- according to the given comparison function on the elements.
minValueBy :: (a -> a -> Ordering) -> Values a -> a
minValueBy cmp s = minimumBy cmp (valuesOf s)

--- Returns the maximum of a non-empty multiset of values
--- according to the given comparison function on the elements.
maxValue :: Ord a => Values a -> a
maxValue s = maximum (valuesOf s)

--- Returns the maximum of a non-empty multiset of values
--- according to the given comparison function on the elements.
maxValueBy :: (a -> a -> Ordering) -> Values a -> a
maxValueBy cmp s = maximumBy cmp (valuesOf s)

--- Puts all elements of a multiset of values in a list.
--- Since the order of the elements in the list might depend on
--- the time of the computation, this operation is an I/O action.
values2list :: Values a -> IO [a]
values2list s = return (valuesOf s)

--- Prints all elements of a multiset of values.
printValues :: Show a => Values a -> IO ()
printValues s = values2list s >>= mapM_ print

--- Transforms a multiset of values into a list sorted by
--- the standard term ordering. As a consequence, the multiset of values
--- is completely evaluated.
sortValues :: Ord a => Values a -> [a]
sortValues = sortValuesBy (<=)

--- Transforms a multiset of values into a list sorted by a given ordering
--- on the values. As a consequence, the multiset of values
--- is completely evaluated.
--- In order to ensure that the result of this operation is independent of the
--- evaluation order, the given ordering must be a total order.
sortValuesBy :: (a -> a -> Bool) -> Values a -> [a]
sortValuesBy leq s = sortBy leq (valuesOf s)

------------------------------------------------------------------------