Unlambda d function - factorial

I think I need some elaboration on how the D function works in unlambda. Right now I'm trying to make a function (factorial) with the Y combinator, but it always results in some kind of infinite loop. Or segfault, depending on the interpreter. I'm pretty sure D is what I want to use here. I tried this:
``d```sii``sii`.xi
and it had the same infinite loop. Does anyone think they could help me understand D in unlambda?
...
In unlambda notation, my function is
```s``s``s`ks``s`kki``s``s`ks`ki`ki``s``s`ks``s`kki``s``s`ks`ki`ki``s`k`s``s``s``s``si`k`ki`k``s``si`k`ki`kk`k`ki`k`s`sk``s`k`s``s`ksk``s``s`ksk`k``s``si`k``s``s``s``si`ki`k`ki`k`ki`s``s`ksk`k`k`kk
Y= ``s``s``s`ks``s`kki``s``s`ks`ki`ki``s``s`ks``s`kki``s``s`ks`ki`ki
Factorial = Y(\xy.0y1(My(x(Sy))))
0 = ``s``s``si`k`ki`k``s``si`k`ki`kk`k`ki (Returns K if it's 0 in church numerals, Returns KI if it's something else.)
M = ``s`ksk (Prefix multiplier of church numerals)
S = ``s``si`k``s``s``s``si`ki`k`ki`k`ki`s``s`ksk`k`k`kk (Decrements a church integer)
I'm pretty sure that if it were evaluated normally, with the left first, it would work, but I'm not sure.
Thanks in advance.

I don't really see how d could help a factorial function, but an illustration of what d does is easy:
`.1` .2i => 21
``.1`d.2i => 12
In the first case, .2 is evaluated before .1, on grounds of the eager evaluation rule.
In the second case, .2 is passed through .1 "protected", only to be evaluated from the outside.

Related

Haskell: Break a loop conditionally

I want to break a loop in a situation like this:
import Data.Maybe (fromJust, isJust, Maybe(Just))
tryCombination :: Int -> Int -> Maybe String
tryCombination x y
| x * y == 20 = Just "Okay"
| otherwise = Nothing
result :: [String]
result = map (fromJust) $
filter (isJust) [tryCombination x y | x <- [1..5], y <- [1..5]]
main = putStrLn $ unlines $result
Imagine, that "tryCombination" is a lot more complicated like in this example. And it's consuming a lot of cpu power. And it's not a evalutation of 25 possibilities, but 26^3.
So when "tryCombination" finds a solution for a given combination, it returns a Just, otherwise a Nothing. How can I break the loop instantly on the first found solution?
Simple solution: find and join
It looks like you're looking for Data.List.find. find has the type signature
find :: (a -> Bool) -> [a] -> Maybe a
So you'd do something like
result :: Maybe (Maybe String)
result = find isJust [tryCombination x y | x <- [1..5], y <- [1..5]]
Or, if you don't want a Maybe (Maybe String) (why would you?), you can fold them together with Control.Monad.join, which has the signature
join :: Maybe (Maybe a) -> Maybe a
so that you have
result :: Maybe String
result = join $ find isJust [tryCombination x y | x <- [1..5], y <- [1..5]]
More advanced solution: asum
If you wanted a slightly more advanced solution, you could use Data.Foldable.asum, which has the signature
asum :: [Maybe a] -> Maybe a
What it does is pick out the first Just value from a list of many. It does this by using the Alternative instance of Maybe. The Alternative instance of Maybe works like this: (import Control.Applicative to get access to the <|> operator)
λ> Nothing <|> Nothing
Nothing
λ> Nothing <|> Just "world"
Just "world"
λ> Just "hello" <|> Just "world"
Just "hello"
In other words, it picks the first Just value from two alternatives. Imagine putting <|> between every element of your list, so that
[Nothing, Nothing, Just "okay", Nothing, Nothing, Nothing, Just "okay"]
gets turned to
Nothing <|> Nothing <|> Just "okay" <|> Nothing <|> Nothing <|> Nothing <|> Just "okay"
This is exactly what the asum function does! Since <|> is short-circuiting, it will only evaluate up to the first Just value. With that, your function would be as simple as
result :: Maybe String
result = asum [tryCombination x y | x <- [1..5], y <- [1..5]]
Why would you want this more advanced solution? Not only is it shorter; once you know the idiom (i.e. when you are familiar with Alternative and asum) it is much more clear what the function does, just by reading the first few characters of the code.
To answer your question, find function is what you need. After you get Maybe (Maybe String) you can transform it into Maybe String with join
While find is nicer, more readable and surely does only what's needed, I wouldn't be so sure about inefficiency of the code that you have in a question. The lazy evaluation would probably take care of that and compute only what's needed, (extra memory can still be consumed). If you are interested, try to benchmark.
Laziness can actually take care of that in this situation.
By calling unlines you are requesting all of the output of your "loop"1, so obviously it can't stop after the first successful tryCombination. But if you only need one match, just use listToMaybe (from Data.Maybe); it will convert your list to Nothing if there are no matches at all, or Just the first match found.
Laziness means that the results in the list will only be evaluated on demand; if you never demand any more elements of the list, the computations necessary to produce them (or even see whether there are any more elements in the list) will never be run!
This means you often don't have to "break loops" the way you do in imperative languages. You can write the full "loop" as a list generator, and the consumer(s) can decide independently how much of the they want. The extreme case of this idea is that Haskell is perfectly happy to generate and even filter infinite lists; it will only run the generation code just enough to produce exactly as many elements as you later end up examining.
1 Actually even unlines produces a lazy string, so if you e.g. only read the first line of the resulting joined string you could still "break the loop" early! But you print the whole thing here.
The evaluation strategy you are looking for is exactly the purpose of the Maybe instance of MonadPlus. In particular, there is the function msum whose type specializes in this case to
msum :: [Maybe a] -> Maybe a
Intuitively, this version of msum takes a list of potentially failing computations, executes them one after another until the first computations succeeds and returns the according result. So, result would become
result :: Maybe String
result = msum [tryCombination x y | x <- [1..5], y <- [1..5]]
On top of that, you could make your code in some sense agnostic to the exact evaluation strategy by generalizing from Maybe to any instance of MonadPlus:
tryCombination :: MonadPlus m => Int -> Int -> m (Int,Int)
-- For the sake of illustration I changed to a more verbose result than "Okay".
tryCombination x y
| x * y == 20 = return (x,y) -- `return` specializes to `Just`.
| otherwise = mzero -- `mzero` specializes to `Nothing`.
result :: MonadPlus m => m (Int,Int)
result = msum [tryCombination x y | x <- [1..5], y <- [1..5]]
To get your desired behavior, just run the following:
*Main> result :: Maybe (Int,Int)
Just (4,5)
However, if you decide you need not only the first combination but all of them, just use the [] instance of MonadPlus:
*Main> result :: [(Int,Int)]
[(4,5),(5,4)]
I hope this helps more on a conceptual level than just providing a solution.
PS: I just noticed that MonadPlus and msum are indeed a bit too restrictive for this purpose, Alternative and asum would have been enough.

Stata: replace, if, forvalues

use "locationdata.dta", clear
gen ring=.
* Philly City Hall
gen lat_center = 39.9525468
gen lon_center = -75.1638855
destring(INTPTLAT10), replace
destring(INTPTLON10), replace
vincenty INTPTLAT10 INTPTLON10 lat_center lon_center , hav(distance_km) inkm
quietly su distance_km
local min = r(min)
replace ring=0 if (`min' <= distance_km < 1)
local max = ceil(r(max))
* forval loop does not work
forval i=1/`max'{
local j = `i'+1
replace ring=`i' if (`i' <= distance_km < `j')
}
I am drawing rings by 1 km from a point. The last part of the code (forval) does not work. Something wrong here?
EDIT:
The result for the forval part is as follows:
. forval i=1/`max'{
2. local j = `i'+1
3. replace ring=`i' if `i' <= distance_km < `j'
4. }
(1746 real changes made)
(0 real changes made)
(0 real changes made)
(0 real changes made)
....
So, replacing does not work for i = 2 and beyond.
A double inequality such as
(`min' <= distance_km < 1)
which makes sense according to mathematical conventions is clearly legal in Stata. Otherwise, your code would have triggered a syntax error. However, Stata does not hold evaluation until the entire expression is evaluated. The parentheses here are immaterial, as what is key is how their contents are evaluated. As it turns out, the result is unlikely to be what you want.
In more detail: Stata interprets this expression from left to right as follows. The first equality
`min' <= distance_km
is true or false and thus evaluated as 0 or 1. Evidently you want to select values such that
distance_km >= `min'
and for such values the inequality above is true and returns 1. Stata would then take a result of 1 forward and turn to the second inequality, evaluating
1 < 1
(i.e. result of first inequality < 1), but that is false for such values. Conversely,
(`min' <= distance_km < 1)
will be evaluated as
0 < 1
-- which is true (returns 1) -- if and only if
`min' > distance_km
In short, what you intend would need to be expressed differently, namely by
(`min' <= distance_km) & (distance_km < 1)
I conjecture that this is at the root of your problem.
Note that Stata has an inrange() function but it is not quite what you want here.
But, all that said, from looking at your code the inequalities and your loop both appear quite unnecessary. You want your rings to be 1 km intervals, so that
gen ring = floor(distance_km)
can replace the entire block of code after your call to vincenty, as floor() rounds down with integer result. You appear to know of its twin ceil().
Some other small points, incidental but worth noting:
You can destring several variables at once.
Putting constants in variables with generate is inefficient. Use scalars for this purpose. (However, if vincenty requires variables as input, that would override this point, but it points up that vincenty is too strict.)
summarize, meanonly is better for calculating just the minimum and maximum. The option name is admittedly misleading here. See http://www.stata-journal.com/sjpdf.html?articlenum=st0135 for discussion.
As a matter of general Stata practice, your post should explain where the user-written vincenty comes from, although it seems that is quite irrelevant in this instance.
For completeness, here is a rewrite, although you need to test it against your data.
use "locationdata.dta", clear
* Philly City Hall
scalar lat_center = 39.9525468
scalar lon_center = -75.1638855
destring INTPTLAT10 INTPTLON10, replace
vincenty INTPTLAT10 INTPTLON10 lat_center lon_center , hav(distance_km) inkm
gen ring = floor(distance_km)

Proving a theorem using induction in COQ

I am learning Coq at school, and I have an assignment to do for home. I have a lemma to proove: If a list contains a zero among its elements, then the product of its elements is 0. I started my code, and I am stuck in a point where I do not know how to go on. I do not know all the commands from Coq, I did a lot of research, but I cannot manage to find my way to the end of the Proof. Here is my code:
Require Import List ZArith.
Open Scope Z_scope.
Fixpoint contains_zero (l : list Z) :=
match l with
nil => false
| a::tl => if Zeq_bool a 0 then true else contains_zero tl
end.
Fixpoint product (l : list Z) :=
match l with
nil => 1
| a::tl => a * product tl
end.
Lemma Zmult_integral_r :
forall n m, m <> 0 -> m * n = 0 -> n = 0.
Proof.
intros n m m0; rewrite Zmult_comm; apply Zmult_integral_l.
assumption.
Qed.
Lemma product_contains_zero :
forall l, contains_zero l = true -> product l = 0.
intros l H.
So, I thought that it would be a good idea to create a function that checks if the list contains a zero, and another one to calculate the product of its elements. I have also found (luckily) a lemma online that prooves that if I have 2 numbers , and I know that one of them is not 0, and their product is 0, then necessarily the other number is 0 (I thought that might help). I thought about doing a proof by induction, but that didn't work out. Any ideas? I know that this is not the place to ask someone to do my work , I AM NOT ASKING THAT, I just need an idea.
1/ You do not need the theorem that you mention, " if I have 2 numbers , and I know that one of them is not 0, and their product is 0, then necessarily the other number is 0". You don't need it because you want to prove that the product is 0, you are not in a situation where you want to use the fact that the product is zero.
So the theorem Zmult_integral_r is not useful for the lemma in this question. It would be useful if you had to prove forall l, product l = 0 -> contains_zero l = true.
Here, for your problem, the two functions that you consider are recursive, so the usual hint is to do a proof by induction, and then to use the tactic simpl to make the functions look simpler.
Represent product of two numbers as one number while you will stand with that lemma.

log (1-var) operation in C

I am trying to code this algorithm. I am stuck in the part of log((1.0-u)/u))/beta;
As I understand, I can not get the result of this in C, as it will always return me with negative value log (returning imaginary value).
Tried to print the result of log(1-5) for instance, it gives me with Nan.
How can I get the result of
double x = (alpha - log((1.0-u)/u))/beta
then?
Would appreciate for any pointers to solve this problem.
Thank you
In that algorithm, u should be uniform random on [0,1], so the quantity (1-u)/u is never negative.
Don't pass in a value of u outside the range (0,1) (this is mentioned in one of the comments in that article). Note that ( and ) denote open (i.e. exclusive) bounds.
As stated you need the range of u to be (0,1) (if u is 0 or 1 you are in trouble). You are probably using rand() in which case you will want
double u = (rand() + 1) / (double)(RAND_MAX + 2);
double x = (alpha - log((1.0-u)/u))/beta
I guess u lays between 0 and 1, thus being a normalized positive random.
log( (1-u)/u ) = log(1-u)-log(u) and thus u needs to be 0<u<1. The graph looks like this
In fact you see the anti-symmetry by u=0.5 you may need to worry only for values between 0 and 0.5, but not including 0. So for u>0.5 you set u=1-u and return -log(1-u)+log(u).

Expressing Loop Iterations as a function of n

I am having trouble with a particular question as follows,
n is an exact power of 3
(n=3^k , where k is a positive integer)
while n > 1
begin
print "hello"
n := n/3
end
I need to find a function of n that will determine how many times 'hello' will be printed.
I am having trouble with it because of the k variable. Is this suppose to be implied within the equation. I realize some test data is n=3 -> 1 ; n=9 -> 2 ; n=27 -> 3 , but it just isn't clicking on how to incorporate k into the solution, if at all. Any push in the right direction would be greatly appreciated. Thanks
yes this is schoolwork, practice problems, but I am not looking for someone to just give me an answer I want to understand how to arrive at it.
Hint: if you have something to exponentiate, what is the reverse
operation?
Logarithms are your friends. =)

Resources