Haskell - unmodified variable in a recursive function - haskell

I have a list of char and integer like [('1',1),('2',2),('3',3),('4',4),('5',5)] and want to turn the integers into the percentage each number count for the total such as [('1',7),('2',13),('3',20),('4',27),('5',33)]. I have tried a recursive function which takes a parameter as (c,i):rest and then divide the i by the total and then call the function with rest. But after every single loop, the total has changed. So is there any way I declare the total from start and use it over and over like other languages.

You need to calculate the total in advance - you can use something like
f :: Integral b => [(a,b)] -> [(a,b)]
f lst = let total = sum $ map snd list
in map (\(x,y) -> (x,(100 * y)`div` total)) lst
Note: it would be a good idea to collect the Integral-values associated to each character beforehand, this makes the output a bit more clear (in my opinion), but this would be an exercise for the astute reader.
To make this function more clear - I would also recommend introducing newtypes for Value and Percentage such that you never try to add values with percentages.
newtype Value a = V {extractV :: a}
newtype Percentage = P {percent :: Integer}
f :: Integral b => [(a,Value b)] -> [(a,Percentage)]

Related

Convert Num to Doublle in Haskell

I am trying to write a function that calculates the average of the values of a list containing type Num.
Here is what I tried:
mean :: Num a => [a] -> Double
mean [] = error "Trying to calculate mean of 0 values"
mean x = sumx / lengthx
where
sumx = fromIntegral (sum x)
lengthx = fromIntegral length x
GHCI rejects the fromIntegral function because it expects an Integral type not a Num.
Is there a way to convert a Num, whatever its specific type, to a Double?
The problem with converting Num a => a to a Double is that a Num may not actually be a number at all. There is no requirement for a member of the Num class to be a number of some sort. You can go and implement an instance of Num for anything, even for unit.
One obvious real-life example is Complex: it has an instance of Num, but a complex number can't always be converted to a real one.
If you want your function to work with integers, just specify Integral as your constraint.
OK, I finally found the way to do this:
mean :: Fractional a => [a] -> a
mean xs = sum xs / fromIntegral (length xs)
This works even if I apply it to a list of Integers. I am not sure why because Fractional does not apply to Integers according to the documentation I have read.
My understanding of Haskell is still obviously quite limited.
A more general way to write it is to use Real:
mean :: (Real a, Fractional b) => [a] -> b
mean xs = realToFrac (sum xs) / fromIntegral (length xs)
But that is not completely satisfactory because this doesn't work on lists of Complex numbers or other non-Real numbers.

Generator, Selector Pattern to calculate approximations in Haskell

I am trying to implement a generator, selector pattern to approximately calculate square roots in haskell
My generator looks like this:
generator :: (Double -> Double) -> Double -> [Double]
generator f a = generator f (f a)
My selector:
selector :: Double -> [Double] -> Double
selector eps (a : b : r)
| abs(a - b) <= eps = b
| otherwise = selector eps (b : r)
And the approx function:
next :: Double -> Double -> Double
next n x = (x + n/x) / 2
Calling this like selector 0.1 (generator (next 5) 2)
should give me ...(next 5( next 5 (next 5 2))) so [2.25, 2.23611111111111, 2.2360679779158,...] since my eps parameter is 0.1 abs(a - b) <= eps should be true on the first execution giving me 2.23611111111111 as a result. I do however end in a endless loop.
Could somebody explain to me what is wrong in the implementation of those functions?
Thanks in advance
This definition
generator f a = generator f (f a)
never generates any list elements: it gets stuck into an infinite recursion instead. You probably want
generator f a = a : generator f (f a)
which makes a to be the first element, followed by all the others we generate using recursion.
It could also be beneficial to avoid putting unevaluated thunks in the list. To avoid that, one could use
generator f a = a `seq` (a : generator f (f a))
so that a is evaluated early. This should not matter much in your code, since the
selector immediately evaluates the thunks as soon as they are generated.
Your generator function is missing the a:, as chi's answer correctly points out. However, there's a better solution than just adding that. Get rid of generator altogether, and use the built-in method iterate instead (or iterate' from Data.List if you want to avoid unevaluated thunks). These methods have the same behavior that you want from generate, but support optimizations like list fusion that your own method won't. And of course, there's also the advantage that it's one less function that you have to write and maintain.

Understanding this type in Haskell?

I'm having some trouble understanding, how this type declaration works.
The type is: (a -> b) -> (b -> c) -> (c -> d) -> a -> d
So, to me I interpret this as a function that takes a function and that function takes another function which outputs a value d.
So, this is how I make my function:
Example :: (a -> b) -> (b -> c) -> (c -> d) -> a -> d
Example f g h x = f ( g ( h (x) )
I'd really appreciate it, if you guys could help me clarify. Thank you!
I think that you already know the theory behind the type you're writing, so I'll try to inject some intuitive way to read it (at least I hope so, your question is not totally clear to me).
When you read something like (a -> b) inside a type, that's a function, as you said. For example (Int -> Bool) is a function.
Let's make an example:
even :: Int -> Bool -- A more generic version of that is in the Prelude
even n = n `rem` 2 == 0
filter :: (Int -> Bool) -> [Int] -> [Int] -- And of that, too
filter _ [] = []
filter f (x:xs)
| f x = x : filter f xs
| otherwise = filter f xs
filteredEven :: [Int]
filteredEven = filter even [1..5] -- it gives [2, 4]
In this example we have a "high order function", a function that get another function and use it in some way.
In a function like the one you're defining you simply use 3 functions (and another parameter). But you can know more.
Each function you declare in the type accept a value returned from the previous one. So a possible solution is the one you have already showed. But the types are generic. There is not a total function that returns a generic value (where total means that it terminate always returning a value different from bottom if all the values are total and different by bottom, so it don't crash or return undefined, for example). So, if you wants a total function you have to have a way to generate the variables requested, from the context of the function (their parameters).
In the example before, using the names used by you, you have to return a value of type d. You only have a way to produce a value of that type, the h function. But to use the h function you have to get a value of type c. You only have the g function for that. But you need a value of type c. Fortunately you have the function f, that in exchange of a value of type a returns the value needed. We have this value (and don't have any other way to obtain a value of that type), so the function can be written. We can't in any way alter the values obtained (call multiple times the functions don't work, for purity and the fact that we have only a way to produce the values), so that's the only way to construct the function, if we wants it to be total:
Example (a -> b) -> (b -> c) -> (c -> d) -> a -> d
Example f g h x = h (g (f x)))
We can write the function in many other ways, but the results they give will be always the same (if Example, f, g and h are total and x is not bottom). So the type can express really well the function, because we can understand how the function works only looking at the type!

Is there a way to unmap in Haskell?

I'm writing a Haskell program. I've created a data type called measurement which is an array of doubles, it looks like this:
data Measurement = Measurement [Double] deriving (Show)
I have a function to cast to Measurement, it takes a list of lists of doubles and will cast it to a list of Measurements. It looks like this:
castToMeasurement :: [[Double]] -> [Measurement]
castToMeasurement = map Measurement
But now I want to do some opereations on the double values. So is there a way I can unmap to an array of doubles? So when I give it a Measurement (or list of Measurements), it will cast it to a list of Doubles (or a list of lists of double). Thanks!
Yes, there is:
data Measurement = Measurement { getMeasurement :: [Double] } deriving Show
castToMeasurement :: [[Double]] -> [Measurement]
castToMeasurement = map Measurement
castFromMeasurement :: [Measurement] -> [[Double]]
castFromMeasurement = map getMeasurement
Simple, isn't it?
Well, no and yes.
The way you phrase the question, whether there's a way to "unmap," the answer would have to be no, not in general. Suppose we have a list of strings:
example1 :: [String]
example1 = ["Hello", "cruel", "world"]
We can use map length to map this to the lengths of the strings:
example2 :: [Int]
example2 = map length example
-- value: [5, 5, 5]
But there is no way to "unmap" the value of example2 to get back the original example1. That would require there to be a function that, given the length, figured out which string the original list had—but that is clearly insufficient information!
But this gives us a hint about what sort of situation we can perform the "unmapping" that you want. If the function that we originally mapped with has an inverse, then we can map with that inverse to "undo" the effect of map. In your case, the Measurement constructor does have an inverse:
-- | The inverse of the 'Measurement' constructor. Laws:
--
-- > Measurement (getMeasurement x) == x
-- > getMeasurement (Measurement xs) == xs
getMeasurement :: Measurement -> [Double]
getMeasurement (Measurement xs) = xs
Since Measurement and getMeasurement are inverses it follows that map Measurement and map getMeasurement are as well, and so:
map getMeasurement (map Measurement xs) == xs
map Measurement (map getMeasurement xs) == xs
Sure you can. Here you can read more about it.
Let think about the function f:
f :: [Double] -> Measurement
f list = Measurement list
It just wraps the constructor of Measurement. I am using new function because it is much easier for me to think about function than about constructors.
Now you need the inverse function to f:
g :: Measurement -> [Double]
g (Measurement list) = list
So now you can construct function:
castFromMeasurement :: [Measurement] -> [[Double]]
castFromMeasurement = map g
It looks a bit ugly. So we can modify it using lambdas:
castFromMeasurement :: [Measurement] -> [[Double]]
castFromMeasurement = map (\(Measurement list) -> list)
But notice that it works only when your data type is not abstract (you have full access to constructor). Also you can redefine your data as follows:
data Measurement = Measurement { getMeasurement :: [Double] } deriving Show
In this case you already have function g = getMeasurement. So castFromMeasurement looks like:
castFromMeasurement :: [Measurement] -> [[Double]]
castFromMeasurement = map getMeasurement
More generally, you can unmap if and only if function f you used to map is reversable.
You got an answer to your question but let's bring math to the table and learn when and how it's possible to unmap.
We're pure functional programmers; that means that the functions we write are very mathematical (which is beyond awesome for many reasons, one of them: it's possible to write this answer). When dealing with functions, the function domain is every possible value of the input type (+ bottom for boxed types). The range, likewise, is every possible value of the output type.
What you are basically asking for is an inverse function for the function in your example (fmap Measurement).
An inverse function for function will "undo" what that function "did".
If I have value x and function f, and the inverse function of f is g, then by definition x = f(g(x))) = g(f(x))). This is probably gibberish, so think about the functions f = (+1) and g = subtract 1, and pick any integer for x. Let's say x=5 for example. f(5) = 6, and now notice how when you apply g -- g(6) = 5 -- you got the number you started off with.You "undid" f by applying the result to g, because g is the inverse of f.
Some functions don't have an inverse function (as Luis Casillas demonstrated in his answer here).
When your function does have, it's up to you to find it. If indeed possible, it's usually it's as difficult as the function you're inversing (e.g. like in the above, plus becomes minus. Like in your example too - your function was simple so the inverse was bound to also be simple).
An easy way to tell if there's an inverse function is to see if there exists a one-to-one mapping between the domain and the range. If there isn't - you lost data when you applied the function and you can't go back. So if an inverse function doesn't exist and you still need to go back, you should find other means. E.g. zip the original value before-hand ((x, f x)), and to get to the original value just apply fst.
Inverse Functions on Khan Academy
Inverse Functions on TheMathPage
Inverse Functions on Wikipedia

Generating an infinite sequence in Haskell

I know that infinite sequences are possible in Haskell - however, I'm not entirely sure how to generate one
Given a method
generate::Integer->Integer
which take an integer and produces the next integer in the sequence, how would I build an infinite sequence out of this?
If you want your sequence to start from 1 then it is -
iterate generate 1
Please notice that first letter of function is lowercase, not uppercase. Otherwise it would be data type, not function.
//edit: I just realized not just data types start with capital, it could be data constructor or type class as well, but that wasn't the point. :)
Adding to Matajon's answer: a way to discover the iterate function other than asking here would be to use Hoogle.
Hoogle's first answer for the query (a -> a) -> [a] is iterate.
Update (2023): Hoogle's scoring appears to have changed and iterate is no longer given with this query. It's full type has another a parameter and with the full type it is given in the results.
There are several ways to do it, but one is:
gen :: (a -> a) -> a -> [a]
gen f s = s : gen f (f s)
This function takes a functon f and some valus s and returns s, after wich it calls itself with that same f, and the result of f s. Demonstration:
Prelude> :t succ
succ :: (Enum a) => a -> a
Prelude> let gen f s = s : gen f (f s)
Prelude> take 10 $ gen succ 3
[3,4,5,6,7,8,9,10,11,12]
In the above example succ acts as the function generate :: Integer -> Integer which you mention. But observe that gen will work with any function of type a -> a.
Edit: and indeed, gen is identical to the function iterate from the Prelude (and Data.List).

Resources