SML - how to return a real from a function with integers? - function

I have the following functions:
fun power(0,n):int = 1 | power(k,n):int = n*power((k-1),n)
fun myfunction(1,n) = 1 | myfunction(2,n) = 1
| myfunction(x,1) = 1 | myfunction(x:int,n:int) = (1 div power(n,(x-1))) + myfunction(x,n- 1)
What I need to do, is return a real value from myfunction, and not an integer. I tried specifying the return value (myfunction(x:int,n:int):real), I have tried using / instead of div, and also tried changing 1's to 1.0 but nothing seems to work.
Any ideas how I should return a real value? (x and n must be integers)

You also need to convert the result of the call to power to real:
fun myfunction(1, n) = 1.0
| myfunction(2, n) = 1.0
| myfunction(x, 1) = 1.0
| myfunction(x, n) = 1.0 / real(power(n, x - 1)) + myfunction(x, n - 1)

You need to convert an int to a real using Real.fromInt. Also, use / instead of div and return 1.0 instead of 1 in the cases where you do it.

Related

Making closures type-stable dependent on the captured variable

For the function
function function_maker(N)
if N == 1
x = 1.0
else
x = 1
end
f(y) = x+y
end
I want the output of this to not be type-stable, but I want it to generate an f that is type-stable, i.e. uses the type of x determined by the value of N to generate a function dependent on N. Basically, I want the functions that come out of this to be performant, but the function_maker itself doesn't need to be performant because it's only used in the global scope or above a function barrier.
f = function_maker(1)
#code_warntype f(1)
Variables:
#self#::#f#9
y::Int64
Body:
begin
return ((Core.getfield)((Core.getfield)(#self#::#f#9, :x)::ANY, :contents)::ANY + y::Int64)::ANY
end::ANY
This doesn't happen by default. I tried f(y) = x::typeof(x)+y but that didn't work either. Is there a simple way to do this?
There's:
julia> function function_maker2(N)
if N == 1
let x = 1.0
return f(y) = x + y
end
else
let x = 1
return f(y) = x + y
end
end
end
function_maker2 (generic function with 1 method)
julia> f2 = function_maker2(1)
(::f) (generic function with 1 method)
julia> #code_warntype f2(1)
Variables:
#self#::#f#5{Float64}
y::Int64
Body:
begin
return (Base.add_float)((Core.getfield)(#self#::#f#5{Float64}, :x)::Float64, (Base.sitofp)(Float64, y::Int64)::Float64)::Float64
end::Float64
This version separates the x in each branch inside let blocks. Otherwise the compiler seems to get confused.

Better way of finding combination for 3 boolean variables

I have 3 bool variables x,y,z. Now at any given moment I can have one out of 2^3=8 combinations as below.
e.g. x=true, y=false and z=false or
x=false, y=true and z=true and so on.
If I see from programming perspective there are 8 cases or may be 8 or greater if else statement to determine what is the combination at that moment.
At any given moment if I want to know what combination is present(given the values of x,y,z) How can I know without using if-else ladder, which makes code logic little bulky. Is there any better/simple logic/way to do it.
If you must handle 8 situations separately. You could encode the value of x, y, z in a variable and then do a switch case on that variable. Pseudo code below -
v = 0
if (x) { v += 4 }
if (y) { v += 2 }
if (z) { v += 1 }
switch (v)
{
case 0 : // all false
case 1 : // z is true
case 2 : // y is true
case 3 : // z and y are true
case 4 : // x is true
...
}
It might be worth using bitwise operators, rather than the numeric value to determine which boolean variables are on or off.
// Assign the bitwise value of each variable
X = 4
Y = 2
Z = 1
// Setting X and Z as true using the bitwise OR operator.
v = X | Z // v = 4 + 1 = 5
// Checking if any of the variables are true using the bitwise OR operator
if (v | X+Y+Z) // v = 4 + 2 + 1 = 7
// Checking if ALL of the variables are true using the bitwise AND operator
if (v & X+Y+Z)
// Checking if variable Y is true using the bitwise OR operator
if (v | Y)
// Checking if variable Y is false using the bitwise OR operator
if (v | Y == false)
// Checking if ONLY variable Y is true using the bitwise AND operator
if (v & Y)
// Checking if ONLY variable Y is false using the bitwise AND operator
if (v & Y == false)
This saves you from messing up the resulting number of a combination of values X, Y, Z. It is also more readable.

Haskell Integer Odd Digits Checker

I seem to be stuck on a question and have no idea how to approach it or what Im doing wrong with my current code.
I have to write a function called oddDigits which takes a single integer argument and returns a boolean result. It should return True if and only if the argument is a positive integer with an odd number of digits. If the argument is zero or negative, the function should stop with an error message.
Also, cant convert the argument into a string. Have to use recursion.
I have a feeling each digit could be stored in a list recursively and then the length of the list could determine the answer.
So far, I have this:
oddDigits :: Integer -> Bool
lst = []
oddDigits x
| (x < 0) || (x == 0) = error
| x `mod` 10 ++ lst ++ oddDigits(x `div` 10)
| length(lst) `mod` 2 /= 0 = True
| otherwise = False
Sorry if the code looks horrible. I am new to Haskell and still learning. What exactly am I doing wrong and how could I correct it?
First off, this seems a pretty weird thing to check. Perhaps what you're doing wrong is to ever consider this problem...
But if you persist you want to know the property of an integer having an odd number of digits... oh well. There's a lot that could be improved. For starters, (x < 0) || (x == 0) doesn't need the parentheses – < and == (infix 4) bind more tightly than ||. If you're not sure about this, you can always ask GHCi:
Prelude> :i ==
class Eq a where
(==) :: a -> a -> Bool
...
-- Defined in ‘GHC.Classes’
infix 4 ==
Prelude> :i ||
(||) :: Bool -> Bool -> Bool -- Defined in ‘GHC.Classes’
infixr 2 ||
But here you don't need || anyway because there's a dedicated operator for less-than-or-equal. Hence you can just write
oddDigits x
| x <= 0 = error "bla bla"
| ...
Then, you can “convert” the number to a string. Converting to string is generally a really frowned-upon thing to do because it throws all structure, typechecking etc. out of the window; however “number of digits” basically is a property of a string (the decimal expansion), rather than a number itself, so this is not entirely unsensible for this specific task. This would work:
oddDigits x
| x <= 0 = error "blearg"
| length (show x)`mod`2 /= 0 = True
| otherwise = False
however it's a bit redundancy department redundant. You're checking if something is True, then give True as the result... why not just put it in one clause:
oddDigits x
| x <= 0 = error "blearg"
| otherwise = length (show x)`mod`2 /= 0
That's perhaps in fact the best implementation.
For any proper, sensible task, I would not recommend going the string route. Recursion is better. Here's what it could look like:
oddDigits 1 = True
oddDigits x
| x <= 0 = error "blearg"
| otherwise = not . oddDigits $ x`div`10
There's nothing wrong with your general approach of converting to a list of digits, then finding the length of the list. Really where you went wrong is trying to cram everything into one function. As you found out first hand, it makes it very difficult to debug. Functional programming works best with very small functions.
If you separate out the responsibility of converting an integer to a list of digits, using a digs function like the one from this answer, the rest of your algorithm simplifies to:
oddDigits x | x <= 0 = error
oddDigits x = odd . length $ digs x
leftaroundabout's eventual answer is very nice, however it fails for numbers like 2,3 and 23. Here's a fix.
oddDigits x
| x <= 0 = error "blearg"
| x < 10 = True
| otherwise = not . oddDigits $ x`div`10
Its much more elegant than my initial answer, below. I'm including it to introduce a common functional paradigm, a worker/wrapper transformation of the problem. Here the wrapper gives the interface and passes off the work to another function. Notice that the negativity check only needs to be done once now.
oddDigits :: Integer -> Bool
oddDigits x
| x <= 0 = False
| otherwise = oddDigits' True x
oddDigits' :: Bool -> Integer -> Bool
oddDigits' t x
| x < 10 = t
| otherwise = oddDigits' (not t) $ x `div` 10
oddDigits' carries a piece of internal data with it, the initial Bool. My first first thought was to have that Bool be a digit accumulator, counting the number of digits. In that case, an "unwrapper" needs to be supplied, in this case the standard "odd" function:
oddDigits x
| x <= 0 = False
| otherwise = odd . oddDigits'' 1 $ x
where oddDigits'' :: Integer -> Integer -> Integer.

Pattern matching on Ints

I am a beginner in learning Haskell, and I wanted to know if you could pattern match on Ints like so:
add x 0 = x
add x (1 + y) = 1 + x + add x y,
Or maybe in this way:
add x 0 = x
add x (successor y) = 1 + x + add x y
There is an extension that lets you do that, but instead you should simply pattern match on y, and subtract 1 manually:
add x y = 1 + x + add x (y - 1)
The extension is called NPlusKPatterns. If you really want to use it (keep in mind it's deprecated in haskell 2010), it can be enabled by either passing a -XNPlusKPatterns parameter to GHC, or putting a {-# LANGUAGE NPlusKPatterns #-} at the top of your file.
Pattern matching isn't arbitrary case analysis. It's a disciplined, but limited form of case analysis, where the cases are the constructors of a data type.
In the specific case of pattern matching integers, the constructors are taken to be the integer values. So you can use integer values as the cases for pattern-matching:
foo 0 = ...
foo 2 = ...
foo x = ...
But you can't use arbitrary expressions. The following code is illegal:
foo (2 * x) = ...
foo (2 * x + 1) = ...
You may know that ever integer is either of the form 2 * x or 2 * x + 1. But the type system doesn't know.
The formatting of your code is a bit off so it is difficult to know what you're asking but you can using pattern matching for input of type Int. An example would be
add x 0 = x
add x y = x + y

Compute next prime number in Haskell

I am trying to compute the next closest prime number after a number is entered with Haskell,
I have coded 2 functions isPrime and nextPrime
Here is my code:
isPrime :: Int -> Bool
isPrime x | x < 2 = False
| otherwise = prime (2:[3,4..(x-1)])
where
prime (y:z)
| x < y ^ 2 = True
| x `mod` y == 0 = False
| otherwise = prime z
nextPrime :: Int -> Int
nextPrime n | isPrime n == True = n
| otherwise = nextPrime n
where
n = n + 1
The problem I have is that I get this error when I run it : * Exception: "<<"loop">>"
I don't know what's wrong, is it an infinite loop?
You cannot change the value of variables in Haskell. This means that you cannot execute
n = n + 1
since that would change the value of n. In Haskell, n is a name that always refers to the same value inside the function it is used. If n starts out as 3, n will always be 3. You could do,
next = n + 1
and then also change
| otherwise = nextPrime n
into
| otherwise = nextPrime next
This will not change the value of any variable, but instead create a new variable with the new value – something you often do in Haskell!
Just change the definition of nextPrime to
nextPrime :: Int -> Int
nextPrime n | isPrime n = n -- don't need to compare to True here
| otherwise = nextPrime (n+1)
You generate an infinite regress when you try to define n = n + 1, as the runtime would attempt to expand this as
n = n + 1
= (n + 1) + 1
= ((n + 1) + 1) + 1
= ...
Fortunately, the compiler is able to detect this kind of infinite regress and warn you about it!