1 {------------------------------------------------------------------------------ 2 RESULTS 3 4 RESULTS which may succeed or fail can be represented in two ways, both of which 5 have important advantages. When only one possible answer is expected, a tagged 6 union allows a value of one type (the answer) to be returned in the case of 7 success, and a value of a different type (a reason) to be returned in case of 8 failure. The Result type is presented here as an (abstract) type with the 9 following functions: 10 11 success a creates a value representing a successful result with value a 12 succeeds x tests a result to see if it is successful 13 answer x extracts the answer from a successful result 14 15 failure r creates a failure value with reason r 16 fails x tests a result to see if it is a failure 17 reason x extracts the reason from a failed result 18 19 There is a potential confusion with the constructors Success and Failure which 20 are used by the IO Response type. The Answer and Reason constructors here are 21 not intended to be used directly in programs. 22 ------------------------------------------------------------------------------} 23 24 module Result where 25 26 data Result a r = Answer a | Reason r 27 28 29 success a = Answer a 30 31 succeeds (Answer a) = True 32 succeeds _ = False 33 34 answer (Answer a) = a 35 36 37 failure r = Reason r 38 39 fails = not . succeeds 40 41 reason (Reason r) = r 42 43 44 -- The second representation of results, invaluable for use in search 45 -- algorithms which may produce many answers, is as a list of successful 46 -- answers. There is no provision for a reason to be given in the case of 47 -- failure, which is represented by []. The `answers' function converts from 48 -- the above representation to the new one, otherwise normal list operations 49 -- are used (eg `null' to test for failure). 50 51 52 answers (Answer a) = [a] 53 answers _ = []