Eiffel: is there a way to express a double implies clause in eiffel? - design-by-contract

Like double bind in psychology, is there a way to tell that one expression implies another and reversely?
valid_last_error: attached last_error implies not attached last_success_message
valid_last_success_message: attached last_success_message implies not attached last_error
would be something like
valid_last_error: attached last_error double_binded_not attached last_success_message
which could be equivalent to
valid_last_error: attached last_error never_with attached last_success_message
T stands for True boolean expression
F for False
R for Result
implies (a, b: BOOLEAN): BOOLEAN
a b R
T T T
T F F
F T T
F F T
and (a, b: BOOLEAN): BOOLEAN
a b R
T T T
T F F
F T F
F F F
or (a, b: BOOLEAN): BOOLEAN
a b R
T T T
T F T
F T T
F F F
xor (a, b: BOOLEAN): BOOLEAN
a b R
T T F
T F T
F T T
F F F
double_implies (a, b: BOOLEAN): BOOLEAN
a b R
T T F
T F T
F T T
F F T
as a maybe more explaining example (more known) instead of writing
invalid_index_implies_off: index < 1 implies off
off_implies_invalid_index: off implies index < 1
we could write:
index_coherent_with_off: index < 1 never_both off
which would just add a function to BOOLEAN class such as
alias never_with, alias reversible_implies (v: like Current): like Current
do
if Current and v then
Result := False
else
Result := True
end
end
Hope now everybody got my point... I don't know if there is such arithmetic operator.
We could extend it for a variable number of parameters

The only answer for my question is to define a function in an util class like
feature -- could be in class BOOLEAN
double_implies, reversible_implies, never_both (a, b: BOOLEAN): BOOLEAN
-- Into boolean class with never_with
do
if a and b then
Result := False
else
Result := True
end
end

Related

Function wrapper/decorator in OCaml

I have a function with the following signature:
val func : a -> b -> c -> d -> e -> f -> unit
and sometimes it raises exceptions. I want to change the control flow so that it looks like this:
val funcw : a -> b -> c -> d -> e -> f -> [ `Error of string | `Ok of unit ]
The way I tried wrapping it is ugly: make another function, funcw, that takes the same amount of arguments, applies func to them, and does try/with. But there must be a better way than that. Thoughts?
You can make f a parameter of the wrapper function. That's a little more general.
let w6 f a b c d e g =
try `Ok (f a b c d e g) with e -> `Error (Printexc.to_string e)
A wrapped version of func is then (w6 func)
This wrapper works for curried functions of 6 arguments, like your func. You can't really define a single wrapper for all the different numbers of arguments (as they have different types), but you can define a family of wrappers for different numbers of arguments like this:
let w1 f x = try `Ok (f x) with e -> `Error (Printexc.to_string e)
let ws f x y =
match f x with
| `Ok f' -> (try `Ok (f' y) with e -> `Error (Printexc.to_string e))
| `Error _ as err -> err
let w2 f = ws (w1 f)
let w3 f x = ws (w2 f x)
let w4 f x y = ws (w3 f x y)
let w5 f x y z = ws (w4 f x y z)
let w6 f x y z w = ws (w5 f x y z w)
There might be a tidier scheme but this seems pretty good.

Why one parameter Ocaml function works with two arguments

I can't understand why the following function works with 2 arguments even if we declare it with one param:
let rec removeFromList e = function
h :: t -> if h=e then h
else h :: removeFromList e t
| _ -> [];;
removeFromList 1 [1;2;3];;
You're declaring it with two parameters. The syntax:
let f = function ...
can be seen as a shortcut for
let f x = match x with
So, your definition is actually:
let rec removeFromList e lst = match lst with
h :: t -> if h=e then h else h :: removeFromList e

Exceptions handling in OCaml

I have to write the function try_finalyze f g y x of type : ('a -> 'b) -> ('b -> 'c) -> 'c -> 'a -> 'c
knowing that:
1. if an exception is raised by f x the returned value has to be y
2. if f x doesn't raise any exception we have to return the result of g applied on f x
exception E
let try_finalyze f g y x = try g (f x) with E -> y;;
val try_finalyze : ('a -> 'b) -> ('b -> 'c) -> 'c -> 'a -> 'c = <fun>
1.Is it right how I treated the problem?
2.In this context what will do the following function:
fun f -> try_finalyze f (fun x-> Some x) None
I don't see the role of a function like (fun x-> Some x)
The answer to your first question is - not really. According to your specification function should catch any exception, not only your exception E. Maybe I'm misreading, but it will be better use the following definition:
let try_finalize f g y x = try g (f x) with exn -> y
As for the second part of the question, there're several ways in OCaml to signal an error. The two most common are:
Raise an exception
Return a value of an option type
The former variant is syntactically lighter, the later doesn't allow a caller to ignore the error condition. Sometimes you need to switch from one variant to an another. Suppose you have a function that raises an exception, and you would like to create a function with the same behavior, but returning an option value. Let's give it a name:
let with_option f = try_finalize f (fun x-> Some x) None
Then we can, for example, convert a List.hd to a function that returns an option type, depending on whether the list is empty or not:
let head x = with_option List.hd x
This function will have type 'a list -> 'a option, compare it with List.hd type 'a list -> 'a, the former will not allow to ignore the empty list case. When applied to an empty list, it will return a None value:
# head [];;
- : 'a option = None
If you write
let try_finalize f g y x = try g (f x) with _ -> y
Your function will return y if f doesn't raise an error but g does, which is not what you said you want.
To ensure that you catch only errors from f you should put f x alone in the try block:
let try_finalize f g y x =
let z = try Some (f x) with _ -> None in
match z with
| Some z -> g z
| None -> y
Exceptions may be considered bad style in a purely functional code, that's why you may want to transform a function that may raise an exception such as List.assoc : 'a -> ('a * 'b) list -> 'b into a function that does the same thing but returns an option.
That's what
let with_option f = try_finalize f (fun x-> Some x) None
does.
If I understand the problem statement correctly, I think I would do this :
let try_finalize f g y x =
try
let v = f x in g v
with _ -> y
As for question 2, suppose you have a function f that takes a value of type v and computes a result of type r. This :
fun f -> try_finalize f (fun x-> Some x) None
returns a function that tries to apply f. If it succeeds (i.e. no exception is thrown), it returns Some r. Otherwise, it returns None. Basically, it transforms a function that may throw an exception into a function that will not throw anything. The new function returns a r option instead of a r.
Maybe like this but the function doesn't have anymore the required type
let try_finalyze f g y x = match f x with
|E -> y
| _ -> g (f x) ;;

Clojure: function arguments/signatures using macro or def

I have many functions of the same long signature (shortened here for simplicity):
(defn f
[x & {:keys [a b c d e f g h]
:or [a false b false c false d false e false f false g false h false]}]
a)
I was hoping to use a macro, function, or even a def to store this common signature beforehand:
(def args `[a b c d e f g h])
(defn args [] `[a b c d e f g h])
(defmacro args [] `[a b c d e f g h])
but all of them, when I plugged into
(defn f
[x & {:keys (args)
:or [a false b false c false d false e false f false g false h false]}]
a)
ended up with errors like
CompilerException java.lang.RuntimeException: Unable to resolve symbol: a in this context, compiling:(NO_SOURCE_PATH:1)
So my two questions are:
Is there any way to define and use such a common args?
If such an args can be defined, I would also like to reduce it in order to get the :or params: [a false b false c false d false e false f false g false h false]. How would this be done? (I'm asking in case a working definition of args might be weird enough that this is no longer straightforward.)
The problem is that the stuff inside the argument vector in a defn doesn't get evaluated. However, you can define your own version of defn, like so:
user=> (defmacro mydefn [name & body] `(defn ~name ~'[a b c] ~#body))
#'user/mydefn
user=> (mydefn f (+ a b))
#'user/f
user=> (f 1 2 4)
3
Note the need for ~' for the arguments. Otherwise syntax-quote (`) would qualify the symbols into user.a etc.

Composing two error-raising functions in Haskell

The problem I have been given says this:
In a similar way to mapMaybe, define
the function:
composeMaybe :: (a->Maybe b) -> (b -> Maybe c) -> (a-> Maybe c)
which composes two error-raising functions.
The type Maybe a and the function mapMaybe are coded like this:
data Maybe a = Nothing | Just a
mapMaybe g Nothing = Nothing
mapMaybe g (Just x) = Just (g x)
I tried using composition like this:
composeMaybe f g = f.g
But it does not compile.
Could anyone point me in the right direction?
The tool you are looking for already exists. There are two Kleisli composition operators in Control.Monad.
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
When m = Maybe, the implementation of composeMaybe becomes apparent:
composeMaybe = (>=>)
Looking at the definition of (>=>),
f >=> g = \x -> f x >>= g
which you can inline if you want to think about it in your own terms as
composeMaybe f g x = f x >>= g
or which could be written in do-sugar as:
composeMaybe f g x = do
y <- f x
g y
In general, I'd just stick to using (>=>), which has nice theoretical reasons for existing, because it provides the cleanest way to state the monad laws.
First of all: if anything it should be g.f, not f.g because you want a function which takes the same argument as f and gives the same return value as g. However that doesn't work because the return type of f does not equal the argument type of g (the return type of f has a Maybe in it and the argument type of g does not).
So what you need to do is: Define a function which takes a Maybe b as an argument. If that argument is Nothing, it should return Nothing. If the argument is Just b, it should return g b. composeMaybe should return the composition of the function with f.
Here is an excellent tutorial about Haskell monads (and especially the Maybe monad, which is used in the first examples).
composeMaybe :: (a -> Maybe b)
-> (b -> Maybe c)
-> (a -> Maybe c)
composeMaybe f g = \x ->
Since g takes an argument of type b, but f produces a value of type Maybe b, you have to pattern match on the result of f x if you want to pass that result to g.
case f x of
Nothing -> ...
Just y -> ...
A very similar function already exists — the monadic bind operator, >>=. Its type (for the Maybe monad) is Maybe a -> (a -> Maybe b) -> Maybe b, and it's used like this:
Just 100 >>= \n -> Just (show n) -- gives Just "100"
It's not exactly the same as your composeMaybe function, which takes a function returning a Maybe instead of a direct Maybe value for its first argument. But you can write your composeMaybe function very simply with this operator — it's almost as simple as the definition of the normal compose function, (.) f g x = f (g x).
Notice how close the types of composeMaybe's arguments are to what the monadic bind operator wants for its latter argument:
ghci> :t (>>=)
(>>=) :: (Monad m) => m a -> (a -> m b) -> m b
The order of f and g is backward for composition, so how about a better name?
thenMaybe :: (a -> Maybe b) -> (b -> Maybe c) -> (a -> Maybe c)
thenMaybe f g = (>>= g) . (>>= f) . return
Given the following definitions
times3 x = Just $ x * 3
saferecip x
| x == 0 = Nothing
| otherwise = Just $ 1 / x
one can, for example,
ghci> saferecip `thenMaybe` times3 $ 4
Just 0.75
ghci> saferecip `thenMaybe` times3 $ 8
Just 0.375
ghci> saferecip `thenMaybe` times3 $ 0
Nothing
ghci> times3 `thenMaybe` saferecip $ 0
Nothing
ghci> times3 `thenMaybe` saferecip $ 1
Just 0.3333333333333333