Clojure: function arguments/signatures using macro or def - function

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.

Related

Implement the functions using map and foldr, haskell

I have two functions. The first one gives true if all elements of the list are zero
allZero :: [Int] -> Bool
allZero [] = False
allZero [0] = True
allZero (x:xs)
| x == 0 && allZero xs = True
|otherwise = False
The second function gives true if at least one element of the list is zero
oneZero :: [Int] -> Bool
oneZero [] = False
oneZero (x:xs)
| x == 0 = True
| otherwise = oneZero xs
Maybe there is another way to solve this problems. For example with map or foldr?
Thank you
foldr function works so:
Suppose, you have list [1, 2, 3]. Let's write this list as (:) 1 ((:) 2 ((:) 3 [])), where each element has type a. Function foldr takes function f of a -> b -> b type and starting element z of b type, and just replace [] to z and : to f. So, foldr f z ((:) 1 ((:) 2 ((:) 3 []))) == f 1 (f 2 (f 3 z)).
So, you can define your functions so:
allZero = foldr (\x -> x == 0 &&) True
oneZero = foldr (\x -> x == 0 ||) False
foldr basically takes your guard as its folding function:
allZero = foldr (\x acc -> x == 0 && acc) True
acc (for accumulator) is the already-computed value of the recursive call. Being right-associative, the first non-zero value in the list short-circuits the evaluation of the fold function on the rest of the list.
(Note that allZero [] == True by convention. The "hypothesis" is that allZero xs is true, with evidence in the form of a non-zero element to falsify the hypothesis. No elements in the list, no evidence to contradict the hypothesis.)
I leave it as an exercise to adapt this to compute oneZero.

Eiffel: is there a way to express a double implies clause in eiffel?

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

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

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