Use haskell NOT JAVA haskell NOT JAVA haskell NOT JAVA haskell NOT JAVA haskell
ID: 3594862 • Letter: U
Question
Use haskell NOT JAVA haskell NOT JAVA haskell NOT JAVA haskell NOT JAVA haskell NOT JAVA
I've wasted a lot of question in this pls make sure you use haskell syntax
write the following code
4 pts) Write a recursive method to compute m(i) = 1 + 1/2 + 1/3, ... + 1/i, where i is an Int
Note: you can use fromIntegral for operations involving both ints and floats for any of the problems.
4 pts) Write a recursive method to compute m(i) = 1/2, + 2/3, ... + i/(i + 1), where i is an Int
4 pts) Using recursion, implement a method that removes the max element from a list of Ints, or one of the max elements if there is more than one. E.g., [1,2,3,3,4] should become [1,2,3,4]
8 pts) Implement a sorting algorithm that finds the max, puts it at the end of the list, then recursively sorts the remainder of the list. You can create/use any helper functions you need, provide that you wrote it yourself, or it's built into Haskell.
Pls type your code here
Explanation / Answer
module Solution(
harmonic,
harmonicAlt,
maxElementPos,
removeMaxElement,
sortAlt
) where
-- Evaluates m(i) = 1 + 1/2 + 1/3, ... + 1/i
harmonic :: Int -> Double
harmonic n
| n == 1 = 1
| otherwise = 1.0/fromIntegral n + harmonic (n-1)
-- Evaluates m(i) = 1/2, + 2/3, ... + i/(i + 1),
harmonicAlt :: Int -> Double
harmonicAlt n
| n == 1 = 1/2
| otherwise = fromIntegral n/(1 + fromIntegral n) + harmonicAlt (n - 1)
-- Position of maxElement in a list
maxElementPos :: [Int] -> Int
maxElementPos [_] = 0
maxElementPos (x:xs) = maxElementPosHelper x 0 1 (xs) where
maxElementPosHelper mx maxpos n [] = maxpos
maxElementPosHelper mx maxpos n (x':xs)
| mx < x' = maxElementPosHelper x' n (n+1) xs
| otherwise = maxElementPosHelper mx maxpos (n+1) xs
-- Remove Max Element from List Recursively
removeMaxElement :: [Int] -> [Int]
removeMaxElement [_] = []
removeMaxElement xs = take n xs ++ drop (n+1) xs where
n = maxElementPos xs
-- sortAlgorithm
sortAlt :: [Int] -> [Int]
sortAlt [] = []
sortAlt [x] = [x]
sortAlt xs = sortAltHelper xs where
sortAltHelper [] = []
sortAltHelper xs' = sortAltHelper (removeMaxElement xs') ++ [xs' !! maxElementPos xs']
main = do
print $ harmonic 10
print $ harmonicAlt 10
print $ removeMaxElement [1,2,3,3,4]
print $ sortAlt [2,3,1,19,8]
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.