1
0
Fork 0
pr3-ws202627/haskell/03-functions/functions.hs

98 lines
2.6 KiB
Haskell
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import Data.Bits (Bits (xor))
-- single parameter
-- mySign x = if x < 0 then -1 else if x > 0 then 1 else 0
-- two parameters
-- ============= pattern matching =================
mySign 0 = 0
mySign x = if x < 0 then -1 else 1
-- ============= guards =================
mySign x
| x > 0 = 1
| x < 0 = -1
| x == 0 = 0
-- | otherwise = 0 auch eine möglichkeit
-- ============= recursive algorithms =================
myFactorial 0 = 1
myFactorial n = n * myFactorial (n - 1)
myFibonacci 0 = 0
myFibonacci 1 = 1
myFibonacci n = myFibonacci (n - 1) + myFibonacci (n - 2)
-- ============= recursive list algorithms ================= Prüfungsrelevant
myReverse [] = []
myReverse (x : xs) = myReverse xs ++ [x]
myLength [] = 0
myLength (x : xs) = 1 + myLength xs
myMap :: (a -> b) -> [a] -> [b]
myMap _ [] = []
myMap f (x : xs) = f x : myMap f xs
myFilter :: (a -> Bool) -> [a] -> [a]
myFilter _ [] = []
myFilter p (x : xs) = if p x then x : myFilter p xs else myFilter p xs
-- myFilter p l = [x | x <- l, p x] als ListCoprehansion
myZip :: [a] -> [b] -> [(a, b)]
myZip _ [] = []
myZip [] _ = []
myZip (x : xs) (y : ys) = (x, y) : myZip xs ys
myDotProduct :: (Num a) => [a] -> [a] -> a
myDotProduct _ [] = 0
myDotProduct [] _ = 0
myDotProduct (x : xs) (y : ys) = x * y + myDotProduct xs ys
-- ============= merge sort =================
merge :: (Ord a) => [a] -> [a] -> [a]
merge [] [] = []
merge d [] = d
merge [] d = d
merge (x : xs) (y : ys)
| x < y = x : merge xs (y : ys)
| otherwise = y : merge (x : xs) ys
myMergeSort :: (Ord a) => [a] -> [a]
myMergeSort [] = []
myMergeSort [x] = [x]
myMergeSort d =
let half = length d `div` 2
left = take half d
right = drop half d
in merge (myMergeSort left) (myMergeSort right)
-- =========== Filter all numbers that can be divided by 10 ===========
canBeDividedByTen x = x `mod` 10 == 0
-- mit Lambdas
tens = filter (\x -> x `mod` 10 == 0) [1 .. 100]
-- ========================== standard deviation using lambdas =====================
-- The standard deviation is a measure of the amount of variation or dispersion of a set of values.
-- It is defined as the square root of the average of the squared differences from the mean.
--
-- Formula:
-- σ = sqrt( (1/N) * Σ (xi - μ)^2 )
-- where:
-- - σ is the standard deviation,
-- - N is the number of values,
-- - xi represents each value,
-- - μ is the mean of the values.
stddev seq =
let n = fromIntegral (length seq)
mean = sum seq / n
in sqrt $ foldl (\acc x -> acc + (x - mean) ^ 2) 0 seq / n
-- ======================= order list of strings by length =================