Haskell function won't work, what am i doing wrong? - haskell

Hi i am trying to remove all multiples of m from a list (ex [2..100])
my Code:
crossOut :: Int -> [Int] -> [Int]
crossOut n ns = [ x | x <- ns , x /= (n*x)]

x /= (n*x) tests if x is n times itself, which isn't going to work. Try x `mod` n /= 0 instead.

Your function, when read in English, would sound like: "any x in ns, where x does not equal n times x, for some input n". Aside from n = 1, this will always be true, and so no elements will be removed.

Related

Counting the occurrences of chararacters in a string

I got the task to count the number of occurrences of each (lower case) character in a string. I am not allowed to use any function of the library, I came up with the following, working solution.
occur :: String -> [(Char,Int)]
occur y = [ (x,count x y) | x<-['a'..'z'], count x y > 0]
I was trying at first:
occur2 :: String -> [(Char,Int)]
occur2 y = [ (x,z) | x<-['a'..'z'], z<- count x y, count x y > 0]
I defined the helper function count like this:
count :: Char -> String -> Int
count k str = length [n | n <- str, n == k]
Two questions:
Why is occur2 not working?
Is there any way to define occur without my aux function count?
occur2 isn't working because count x y is not a list, so it can't be used for a generator expression like in z <- count x y. Instead, use a let expression.
You can remove the count definition by inlining it.
occur :: String -> [(Char,Int)]
occur y = [ (x,z) | x <- ['a'..'z'], let z = length [n | n <- y, n == x], z > 0]
If you were to use libraries, a simple and efficient implementation would be to use a MultiSet.
import qualified Data.MultiSet as MS
occur :: String -> [(Char,Int)]
occur = MS.toAscOccurList . MS.fromList . filter (\c -> c >= 'a' && c <= 'z')

Project Euler #24 in Haskell

I am trying to solve the problems from Project Euler using Haskell, but I got sucked at #24
I'm trying to use factorials to solve problem but just can't work for the last three digits, here is my code:
import Data.List
fact n = product [n, n-1 .. 1]
recur :: Int -> Int -> [Int] -> [Int]
recur x y arr
| y > 1 = arr !! d : recur r (y-1) (delete (arr !! d) arr)
| otherwise = arr
where d = x `div` fact y
r = x `mod` fact y
main::IO()
main = print(recur 1000000 9 [0..9])
(I know it is now not really "functional")
I managed to get result [2,7,8,3,9,1,4,5,0,6], while the right answer I accidently figured out by hand is 2783915460.
I just want to know why this algorithm doesn't work for the last three digits. Thanks.
Unadulterated divMod is wrong for this algorithm. You need
dvm x facty | r == 0 = (d-1, facty)
| otherwise = (d, r)
where
(d, r) = divMod x facty
instead:
recur x y arr
.......
.......
where (d, r) = x `dvm` fact y
We cannot have zero combinations to do left. Zero means none.
Also the pattern guard condition should be changed to y > 0. Only when the length of the remaining choices list is 1 (at which point y is 0) there's no more choices to be made and we just use the last available digit left.

Create a list of divisible integers in haskell

I'm new to haskell and I'm trying to create an expression, that gives a list of integers from 0 to n, which are divisible by 3. The script I wrote doesn't work and I'm not sure for what reason.
zeroto :: Int -> [Int]
zeroto n = [x | x <- [0..n]]
where
x "mod" 3 == 0
where doesn't work like that. It's not a filter -- it's locally-scoped definitions.
However, a list comprehension does allow for filters, you've just not put it in the right place.
zeroto :: Int -> [Int]
zeroto n = [x | x <- [0..n], x `mod` 3 == 0]
Alternatively, you could define a filter function in the where block and filter afterwards, but this is kind of silly.
zeroto :: Int -> [Int]
zeroto n = divisibleByThree [0..n]
where divisibleByThree = filter (\x -> x `mod` 3 == 0)
This is not the best way but using simple recursion it can be done as
mod3Arr :: Int -> [Int]
mod3Arr 0 = [0]
mod3Arr n | nmod3 == 0 = smallerArr ++ [n]
| otherwise = smallerArr
where smallerArr = mod3Arr ( n - 1)

Haskell reverse Integer with recursion

I want to reverse an Integer in Haskell with recursion. I have a small issue.
Here is the code :
reverseInt :: Integer -> Integer
reverseInt n
| n>0 = (mod n 10)*10 + reverseInt(div n 10)
| otherwise = 0
Example 345
I use as input 345 and I want to output 543
In my program it will do....
reverseInt 345
345>0
mod 345 10 -> 5
reverseInt 34
34
34>0
mod 34 10 -> 4
reverseInt 3
3>0
mod 3 10 -> 3
reverseInt 0
0=0 (ends)
And at the end it returns the sum of them... 5+4+3 = 12.
So I want each time before it sums them, to multiple the sum * 10. So it will go...
5
5*10 + 4
54*10 + 3
543
Here's a relatively simple one:
reverseInt :: Int -> Int
reverseInt 0 = 0
reverseInt n = firstDigit + 10 * (reverseInt $ n - firstDigit * 10^place)
where
n' = fromIntegral n
place = (floor . logBase 10) n'
firstDigit = n `div` 10^place
Basically,
You take the logBase 10 of your input integer, to give you in what place it is (10s, 100s, 1000s...)
Because the previous calculation gives you a floating point number, of which we do not need the decimals, we use the floor function to truncate everything after the decimal.
We determine the first digit of the number by doing n 'div' 10^place. For example, if we had 543, we'd find place to be 2, so firstDigit = 543/100 = 5 (integer division)
We use this value, and add it to 10 * the reverse of the 'rest' of the integer, in this case, 43.
Edit: Perhaps an even more concise and understandable version might be:
reverseInt :: Int -> Int
reverseInt 0 = 0
reverseInt n = mod n 10 * 10^place + reverseInt (div n 10)
where
n' = fromIntegral n
place = (floor . logBase 10) n'
This time, instead of recursing through the first digit, we're recursing through the last one and using place to give it the right number of zeroes.
reverseInt :: Integer -> Integer
reverseInt n = snd $ rev n
where
rev x
| x>0 = let (a,b) = rev(div x 10)
in ((a*10), (mod x 10)*a + b)
| otherwise = (1,0)
Explanation left to reader :)
I don't know convenient way to found how many times you should multiply (mod n 10) on 10 in your 3rd line. I like solution with unfoldr more:
import Data.List
listify = unfoldr (\ x -> case x of
_ | x <= 0 -> Nothing
_ -> Just(mod x 10, div x 10) )
reverse_n n = foldl (\ acc x -> acc*10+x) 0 (listify n)
In listify function we generate list of numbers from integer in reverse order and after that we build result simple folding a list.
Or just convert it to a string, reverse it and convert it back to an integer:
reverseInt :: Integer -> Integer
reverseInt = read . reverse . show
More (not necessarily recursion based) answers for great good!
reverseInt 0 = 0
reverseInt x = foldl (\x y -> 10*x + y) 0 $ numToList x
where
numToList x = if x == 0 then [] else (x `rem` 10) : numToList (x `div` 10)
This is basically the concatenation of two functions : numToList (convert a given integer to a list 123 -> [1,2,3]) and listToNum (do the opposite).
The numToList function works by repeatedly getting the lowest unit of the number (using rem, Haskell's remainder function), and then chops it off (using div, Haskell's integer division function). Once the number is 0, the empty list is returned and the result concatenates into the final list. Keep in mind that this list is in reverse order!
The listToNum function (not seen) is quite a sexy piece of code:
foldl (\x y -> 10*x + y) 0 xs
This starts from the left and moves to the right, multiplying the current value at each step by 10 and then adding the next number to it.
I know the answer has already been given, but it's always nice to see alternative solutions :)
The first function is recursive to convert the integer to a list. It was originally reversing but the re-conversion function reversed easier so I took it out of the first. The functions can be run separately. The first outputs a tuple pair. The second takes a tuple pair. The second is not recursive nor did it need to be.
di 0 ls = (ls,sum ls); di n ls = di nn $ d:ls where (nn,d) = divMod n 10
di 3456789 []
([3,4,5,6,7,8,9],42)
rec (ls,n) = (sum [y*(10^x)|(x,y) <- zip [0..] ls ],n)
Run both as
rec $ di 3456789 []
(9876543,42)

Weird output from Haskell until function

I'm writing a bit of code to help me with some math stuff. I'm trying to implement the Miller test, not Miller-Rabin, and I need to make a list of a bunch of exponents. Here's the code so far. It inserts the last result twice for some reason, and I don't know why. I must not understand how the until function works.
import Math.NumberTheory.Powers
divides::Integer->Integer->Bool
divides x y = y `mod` x == 0
factorcarmichael::Integer->(Integer,Integer)
factorcarmichael n = until (\(_, s) -> not $ divides 2 s)
(\(r, s) -> (r+1, div s 2))
(0, n-1)
second::((Integer,Integer),[Integer])->[Integer]
second (x,xs) = xs
millerlist::Integer->Integer->[Integer]
millerlist a n = second $ until (\((r,s), xs) -> r<0)
(\((r,s), xs) -> ((r-1,s), (powerMod a ((2^r)*s) n):xs))
(factoredcarmichael, [])
where
factoredcarmichael = factorcarmichael n
Also, the millerlist function is a little kludgy. If someone can suggest an alternative, that would be nice.
The output I'm getting for
millerlist 8888 9746347772161
repeats the last element twice.
That is because
7974284540860^2 ≡ 7974284540860 (mod 9746347772161)
so the number appears twice in the list. But your list is one too long, I believe. I think you only want the remainder of a^(2^k*s) modulo n for 0 <= k < r.
As for alternatives, is there a particular reason why you're not using Math.NumberTheory.Primes.isStrongFermatPP? If you're only interested in the outcome, that's less work coding.
If you want to generate the list, what about
millerlist a n = go r u
where
(r,s) = factorcarmichael n
u = powerMod a s n
go 0 m = []
go k m = m : go (k-1) ((m*m) `mod` n)
or
millerlist a n = take (fromInteger r) $ iterate (\m -> (m*m) `mod` n) u
where
(r,s) = factorcarmichael n
u = powerMod a s n

Resources