From Ranges in Haskell (GHCi) it's pretty much clear why the [2, 2..20] generate infinity list.
The next value is the same, that why this code produces infinity list.
And looks like it doesn't care about limit because of [2, 2..2] generate also infinity list.
Question:
Why the following code [2, 2..(-20)] generate empty list instead?
In short: This is intended behavior.
The [x, y..z] expression is syntactical sugar for enumFromThenTo x y z with enumFromThenTo :: a -> a -> a -> [a].
For Integers it is implemented like:
instance Enum Integer where
# ...
enumFromThenTo x y lim = enumDeltaToInteger x (y-x) lim
So it will call enumDeltaToInteger 2 0 (-20). The enumDeltaToInteger is implemented with [src]:
enumDeltaToInteger :: Integer -> Integer -> Integer -> [Integer]
enumDeltaToInteger x delta lim
| delta >= 0 = up_list x delta lim
| otherwise = dn_list x delta lim
Soo it is considered to be an up_list, and the up_list will increase until it has reached a value larger than lim:
up_list :: Integer -> Integer -> Integer -> [Integer]
up_list x0 delta lim = go (x0 :: Integer)
where
go x | x > lim = []
| otherwise = x : go (x+delta)
This is how it has been described in the Haskell'10 report on the Enum class:
The sequence enumFromThenTo e1 e2 e3 is the list [e1,e1 + i,e1 + 2i,…e3], where the increment, i, is e2 − e1. If the increment is positive or zero, the list terminates when the next element would be greater than e3; the list is empty if e1 > e3. If the increment is negative, the list terminates when the next element would be less than e3; the list is empty if e1 < e3.
So the document says that if the "step" is zero or more, and e1 > e3, then the result is the empty list.
It is indeed a "tricky" case however. I personally agree that using a special case for 0 as "step" would make sense (although I'm not per se saying this is more favorable than using the up_list implementation). It is however how things are defined.
Related
I am new to haskell code. I tried to compute the sum of squares of negative integer in a list using foldr high order.
sumsq :: Int -> Int
sumsq n = foldr op 0 [1..n]
where op x y = x*x + y
Please help to explain each line of code and give any solution if error in this code
When using "where", important to follow the indentation rule.
Here lambda will be appropriate
sumsq n = foldr (\x y -> x*x + y) 0 [1..n]
New to SML, trying to round up a real number to nth decimal, by declaring a function round(n,L), where L is a list of real numbers and n decide the nth decimal that can round up to.
My approach is to convert the real number to a string first, and then get the substring to the nth decimal and then parse the substring back to real number, this works fine if I only want to get the real number to nth decimal, but if I have a number like 0.3456 which I want to round to 0.35, my method won't really achieve that.
fun rd(_,[]) = []
|rd(a:int, x::y:real list) =
if x>0.0
then Option.getOpt(Real.fromString(String.substring(Real.toString(x),0,a+2)),0.0) :: rd(a,y)
else Option.getOpt(Real.fromString(String.substring(Real.toString(x),0,a+3)),0.0) :: rd(a,y)
The expected result is like this:
- rd (2, [0.1234, 0.2345, ~0.3456]);
val it = [0.12,0.23,~0.35] : real list`
But the actual output I got is
val it = [0.12,0.23,~0.34] : real list
If I want to round up the number, is there any good approach?
I've also tried this:
fun rd(_,[]) = []
|rd(a:int, x::y:real list) =
let
val n = real(round(x*Math.pow(10.0,real(a)))) / Math.pow(10.0,real(a))
in n::rd(a,y)
end;
but this solution will give me an uncaught exception overflow...
trying to round up a real number to nth decimal
declaring a function round(n,L), where L is a list of real numbers and n decide the nth decimal
Judging by your use of Math.pow(10.0,real(a)) in your second attempted solution, you seem to be on track. I don't understand where a list comes in; as Yawar points out, try and solve this for rounding a single real, and then apply that recursively (using map) to a list of reals.
So a function
fun roundN (x, n) = ...
fun roundManyN (xs, n) = map (fn x => roundN (x, n)) xs
Start by making some examples and encode them as tests. Since you can't compare real for equality in those tests, start by making (or copying) a custom equality operator.
fun nearlyEqual (a, b, eps) =
let val absA = Real.abs a
val absB = Real.abs b
val diff = Real.abs (a - b)
in Real.== (a, b) orelse
( if Real.== (a, 0.0) orelse
Real.== (b, 0.0) orelse
diff < Real.minNormalPos
then diff < eps * Real.minNormalPos
else diff / Real.min (absA + absB, Real.maxFinite) < eps )
end
val test_roundN_1 =
let val got = roundN (3.14159, 1)
val expected = 3.1
in nearlyEqual (got, expected, 0.1) end
val test_roundN_2 =
let val got = roundN (3.14159, 2)
val expected = 3.14
in nearlyEqual (got, expected, 0.01) end
(* rounding point *)
val test_roundN_3 =
let val got = roundN (3.14159, 3)
val expected = 3.142
in nearlyEqual (got, expected, 0.001) end
(* rounding point *)
val test_roundN_4 =
let val got = roundN (3.14159, 4)
val expected = 3.1416
in nearlyEqual (got, expected, 0.0001) end
val test_roundN_5 =
let val got = roundN (3.14159, 5)
val expected = 3.14159
in nearlyEqual (got, expected, 0.00001) end
You also have some edge cases that you eventually want to deal with:
When n is zero or negative, or when n is greater than the number of digits in the fraction.
When x is close to a rounding point, e.g. roundN (3.1451, 2) ~> 3.15.
When x·10ⁿ has a magnitude that exceeds the size of an int.
When n is so large that a magnitude change may affect the precision of a real.
For a better testing library, check out testlib.sml (and its use in test.sml) in this exercism exercise.
Extracting your second solution into a function, and giving Math.pow (10.0, real n) a temporary binding, you get the solution:
fun roundN (x, n) =
let val m = Math.pow(10.0, real n)
in real (round (x * m)) / m end
this solution will give me an uncaught exception overflow
On what input, I might ask.
One source could be that round : real -> int is a partial function: There are real values that cannot be expressed as int, such as Real.posInf, Real.negInf, 1e10 (on 32-bit SML) and 1e19 (on 64-bit SML). To avoid this, consider using Real.realRound : real -> real to avoid the int conversion.
One way to avoid errors related to x * Math.pow(10.0, real n) causing imprecision because the number grows too big, could be to strip the integer part before multiplying, and adding the integer part back after dividing.
I'm making a program that, for a given integer n, returns a list of a pair of integers, where the first element is a prime from the prime factorization of n, and the second element is the corresponding exponent of that prime. For example for n = 50, it would output [(2,1),(5,2)], since 50 =(2^1)*(5^2).
So anyway, this is my code:
--returns all numbers that divide x
divis :: Integer -> [Integer]
divis 1 = []
divis x = [n | n<-[2..(x-1)], mod x n == 0]
--checks if a number is prime
isprime :: Integer -> Bool
isprime 1 = False
isprime n = if divis n == [] then True else False
--list of prime numbers that divide x
facto :: Integer -> [Integer]
facto 1 = []
facto x = [n | n <- (divis x), isprime n == True]
--finds the biggest exponent of a number m that divides another number n
potencia :: Integer -> Integer -> Integer
potencia _ 0 = error "error"
potencia _ 1 = error "error"
potencia n m = (head [x | x <- [0..], not(mod n (m^x) == 0)]) - 1
The next step would be that, for a number n, I can put togheter in a pair for each number in facto n its corresponding exponent, and output that.
I have tried with this:
factorizar :: Integer -> [(Integer, Integer)]
factorizar 0 = error "nope"
factorizar 1 = [(1,1)] --This isn't accurate but I'll change it later
factorizar n = [(x,y) | x<-(facto n), y == potencia n x, mod n (x^y) == 0] --THIS
I know, the y part in the set comprehension is ugly everywhere. The thing is I dont know what to use since for defining y I need to use x as well, but it is part of the set comprehension. I have tried changing it, or using 'where' but it always has a problem with 'y', telling me it's not in the scope or something. What could be an elegant solution for this?
The simple answer is
y == potencia n x
should really read
let y = potencia n x
and you don't need to check that mod n (x^y) == 0 - I think it is going to be true by definition of potencia.
There are other things you could do differently, but they are tidy-ups.
Why does the exponential operator use float variables in OCaml?
Shouldn't it allow int variables too?
# 3**3;;
Error: This expression has type int but an expression was expected of type
float
Works:
# 3.0**3.0;;
- : float = 27.
So, the existing answers go into how to get around this, but not into why it is the case. There are two main reasons:
1) OCaml doesn't have operator aliasing. You can't have two operators that do the "same thing", but to different types. This means that only one kind of number, integers or floats (or some other representation) will get to use the standard ** interface.
2) pow(), the exponentiation function has historically been defined on floats (for instance, in Standard C).
Also, for another way to get around the problem, if you're using OCaml Batteries included, there is a pow function defined for integers.
You can use int
let int_exp x y = (float_of_int x) ** (float_of_int y) |> int_of_float
There's a similar question: Integer exponentiation in OCaml
Here's one possible tail-recursive implementation of integer exponentiation:
let is_even n =
n mod 2 = 0
(* https://en.wikipedia.org/wiki/Exponentiation_by_squaring *)
let pow base exponent =
if exponent < 0 then invalid_arg "exponent can not be negative" else
let rec aux accumulator base = function
| 0 -> accumulator
| 1 -> base * accumulator
| e when is_even e -> aux accumulator (base * base) (e / 2)
| e -> aux (base * accumulator) (base * base) ((e - 1) / 2) in
aux 1 base exponent
list comprehension haskell
paar = [(a,b) | a<-[a | a<-[1..], mod a 3 == 0], b<-[b*b | b<-[1..]]]
a = divisor 3
b = square
The Elements must be constructed by equitable order.
the test >elem (9, 9801) must be True
my Error
Main> elem (9, 9801) test
ERROR - Garbage collection fails to reclaim sufficient space
How can I implement this with Cantor's diagonal argument?
thx
Not quite sure what your goal is here, but here's the reason why your code blows up.
Prelude> let paar = [(a,b) | a<-[a | a<-[1..], mod a 3 == 0], b<-[b*b | b<-[1..]]]
Prelude> take 10 paar
[(3,1),(3,4),(3,9),(3,16),(3,25),(3,36),(3,49),(3,64),(3,81),(3,100)]
Notice you're generating all the (3, ?) pairs before any other. The elem function works by searching this list linearly from the beginning. As there are an infinite number of (3, ?) pairs, you will never reach the (9, ?) ones.
In addition, your code is probably holding on to paar somewhere, preventing it from being garbage collected. This results in elem (9, 9801) paar taking not only infinite time but also infinite space, leading to the crash you described.
Ultimately, you probably need to take another approach to solving your problem. For example, something like this:
elemPaar :: (Integer, Integer) -> Bool
elemPaar (a, b) = mod a 3 == 0 && isSquare b
where isSquare = ...
Or alternatively figure out some other search strategy than straight up linear search through an infinite list.
Here's an alternate ordering of the same list (by hammar's suggestion):
-- the integer points along the diagonals of slope -1 on the cartesian plane,
-- organized by x-intercept
-- diagonals = [ (0,0), (1,0), (0,1), (2,0), (1,1), (0,2), ...
diagonals = [ (n-i, i) | n <- [0..], i <- [0..n] ]
-- the multiples of three paired with the squares
paar = [ (3*x, y^2) | (x,y) <- diagonals ]
and in action:
ghci> take 10 diagonals
[(0,0),(1,0),(0,1),(2,0),(1,1),(0,2),(3,0),(2,1),(1,2),(0,3)]
ghci> take 10 paar
[(0,0),(3,0),(0,1),(6,0),(3,1),(0,4),(9,0),(6,1),(3,4),(0,9)]
ghci> elem (9, 9801) paar
True
By using a diagonal path to iterate through all the possible values, we guarantee that we reach each finite point in finite time (though some points are still outside the bounds of memory).
As hammar points out in his comment, though, this isn't sufficient, as it will still take
an infinite amount of time to get a False answer.
However, we have an order on the elements of paar, namely (3*a,b^2) comes before (3*c,d^2) when
a + b < c + d. So to determine whether a given pair (x,y) is in paar, we only have to check
pairs (p,q) while p/3 + sqrt q <= x/3 + sqrt y.
To avoid using Floating numbers, we can use a slightly looser condition, that p <= x || q <= y.
Certainly p > x && q > y implies p/3 + sqrt q > x/3 + sqrt y, so this will still include any possible solutions, and it's guaranteed to terminate.
So we can build this check in
-- check only a finite number of elements so we can get a False result as well
isElem (p, q) = elem (p,q) $ takeWhile (\(a,b) -> a <= p || b <= q) paar
And use it:
ghci> isElem (9,9801)
True
ghci> isElem (9,9802)
False
ghci> isElem (10,9801)
False