Casting [Int] to [Double] from input - haskell

I have a list of constants and degrees of a polynomial equation and want to return a list of this composition for a value be applied and then summed. But this list comes as Int and my function expects a list of double.
poly :: [Double] -> [Double] -> [Double -> Double]
poly a b =
let f x y = (*x) . (**y)
in uncurry f <$> zip a b
-- does not work
poly ([1,2,3]:: [Double]) ([1,2,3]:: [Double])
How to cast a list of int to list of double?

You can use fromIntegral, which will convert from any Integral type into any Numeric type (Int, Integer, Rational, and Double).
More here: https://wiki.haskell.org/Converting_numbers

With #4castle and Victoria Ruiz I came up with the following:
poly :: [Int] -> [Int] -> [Double -> Double]
poly = zipWith $ \x y -> (* (fromIntegral x)) . (** (fromIntegral y))
apply :: Double -> [Double -> Double] -> Double
apply x b = sum $ ($x) <$> b
-- l=left limiting, r=right limiting, a=coeficients, b=degrees
solve :: Int -> Int -> [Int] -> [Int] -> [Double]
solve l r a b =
let h = 0.001
linspace = [fromIntegral l,fromIntegral l+h..fromIntegral r]
p = poly a b
area = sum $ map ((*h) . (`apply` p)) linspace
volume = h * (sum $ map ((*pi) . (**2) .(`apply` p)) linspace)
in [area,volume]
I think Haskell compiler with his strong type inference has some peculiarities that can't be directly solved by type cast.

Related

Foldl with lambda expresion

Hi I'm trying to sum a list of tuples into a tuple with the foldl function,
I tryed it with using as parameter a lambda expresion but it's giving out a wrong value
here the code:
data Point = Point {x,y :: Float}
sumPoint :: [Point] -> (Float,Float)
sumPoint xs = foldl (\(a,b) x-> (0+a,0+b)) (0.0,0.0) xs
It should come out sumPoint [Point 2 4, Point 1 2, Point (-1) (-2)] = (2.0,4.0)
But im getting (0.0,0.0)
How is this making any sense?
To be a little structural you better define operations among Point type values and then convert the Point type to Tuple wherever needed. Otherwise you may directly use Tuple and discard the Point type.
data Point = Point {x,y :: Float} deriving Show
toTuple :: Point -> (Float, Float)
toTuple p = (x p, y p)
addPts :: Point -> Point -> Point
addPts p q = Point (x p + x q) (y p + y q)
sumPts :: [Point] -> Point
sumPts = foldl addPts (Point 0 0)
So what you need is toTuple . sumPts function.
*Main> :t toTuple . sumPts
toTuple . sumPts :: [Point] -> (Float, Float)
I changed it to
sumPoint xs = foldl (\(a,b) (Point x y)-> (x+a,y+b)) (0.0,0.0) xs
The problem was I was ignoring the x and at 0+a is nothing happening.

Haskell strange `zip` error

I'm trying to zip two [[Float]] arrays, and then preform a calculation on each element. The resulting zip-ed array will have type [([Float], [Float])], I think.
But I keep on getting an error where Haskell tells me:
[1 of 1] Compiling Mod ( Mod.hs, interpreted )
NN.hs:38:42:
Couldn't match type ‘[Float]’ with ‘Float’
Expected type: [Float]
Actual type: [[Float]]
In the second argument of ‘zip’, namely ‘bs’
In the second argument of ‘map’, namely ‘(zip ws bs)’
Failed, modules loaded: none.
I can't seem to figure out a MCVE, because this is what if (kinda/sorta) trying to do:
feedforward :: ([[Float]], [[Float]]) -> Float -> [Float]
feedforward (ws, bs) a = map (equation a) (zip ws bs)
where equation a (w, b) = (sum $ zipWith (*) w b) + a
But that actually compiles! Whereas my real code looks like this:
data NNetwork = NNetwork { nlayers :: Int
, sizes :: [Int]
, biases :: [[Float]]
, weights :: [[Float]] }
deriving (Show, Ord, Eq)
toFloat x = fromIntegral x :: Float
sig :: Float -> Float
sig a = 1 / (1 + exp (-a))
feedforward :: NNetwork -> Float -> [Float]
feedforward net a = map (eq22 a) (zip ws bs)
where bs = biases net
ws = weights net
dot a b = sum $ zipWith (*) a b
rep a b = replicate (length a) b
eq22 a (w, b) = sig $ (dot w (rep w a)) + b
And yet it doesn't work!
- Thanks in advance
The problem is:
eq22 :: Float -> ([Float], [Float]) -> Float
eq22 a (w, b) = sig $ (dot w (rep w a)) + b
Except that in this context b is a [Float] and used as a Float (see + b). Did you mean some sort of function over b?
Also, these are not arrays, but lists.

Converting `do` Notation `addStuff` to `>>=`

Learn You a Haskell presents the addStuff function:
import Control.Monad.Instances
addStuff :: Int -> Int
addStuff = do
a <- (*2) -- binds (*2) to a
b <- (+10) -- binds (+10) to b
return (a+b) -- return has type sig: 'Monad m => a -> m a'
Are the types of a, b, and return (a+b) all Int -> Int? I think so, but I'm not sure how bind-ing plays a role.
I tried to implement it using >>=, but I'm not sure how to complete it (hence ...).
addStuff' :: Int -> Int
addStuff' = (*2) >>= (+10) >>= ...
Please give me a hint to complete it, as well as edit my understanding of the do notation version.
As I understand, the ... needs to include a type of Int -> Int. In the do version, I could use a and b, but I'm not sure how to add them with the >>= version.
When working with the reader monad (a.k.a. the function monad), you have the type a -> b, which can be rewritten as (->) a b. The actual monad instance here is
instance Monad ((->) r) where
return x = const x
f >>= g = \r -> g (f r) r
Notice that during >>=, the type is
(>>=) :: ((->) r a) -> (a -> ((->) r b)) -> ((->) r b)
Which can be rewritten as
(>>=) :: (r -> a) -> (a -> (r -> b)) -> (r -> b)
Or even
(>>=) :: (r -> a) -> (a -> r -> b) -> (r -> b)
So as you can see, what >>= does is take a single input, apply that to f, and then apply that result to g to produce a new function r -> b. So for your example, you could use:
addStuff' :: Int -> Int
addStuff' = (*2) >>= (+)
And so addStuff' 10 == 30, since it performs the computation (10 * 2) + (10). Note how 10 is fed both to (*2) and (+), and the result of (10*2) is fed to (+) as well. It might make things a little more clear to see it as
test :: Int -> (Int, Int, Int)
test = do
x <- (*2)
y <- (*3)
z <- (*5)
return (x, y, z)
And it's result would be
> test 1
(2, 3, 5)
> test 10
(20, 30, 50)
What this essentially is doing is taking the argument to test "before" it's been applied, feeding it to each of the functions on the right hand side of the <-s, and then combining that result in the return.
So how can you write these without do notation? You could do something like
test :: Int -> (Int, Int, Int)
test =
(\r -> r * 2) >>= (\x ->
(\r -> r * 3) >>= (\y ->
(\r -> r * 5) >>= (\z ->
return (x, y, z))))
Which, admittedly, is not very readable, even with formatting, but the gist is basically that r gets fed to each intermediate function, which produces a result, and a couple nested lambda expressions later you return all three of those results in a tuple.
With a bit of simplification, you could also make each of those nested lambdas into two arguments lambdas:
test =
(\r -> r * 2) >>=
(\x r -> r * 3) >>=
(\y r -> r * 5) >>=
(\z r -> const (x, y, z) r)
I've also replaced the last \z -> return (x, y, z) with its equivalent \z -> const (x, y, z) => \z r -> const (x, y, z) r, just so they all have the same form.
As a rough rule if you want to manually desugar do-notation, first erase the do at the top and flip the bind arrow (<-) on the left-hand-side to a (>>=) on the right-hand-side with the variable on the left as a lambda variable on the right. So:
addStuff :: Int -> Int
addStuff = do
a <- (*2)
... rest ...
Becomes:
addStuff :: Int -> Int
addStuff =
(*2) >>= (\a ->
... rest ...
)
This is recursive, so the next term in the do-notation then becomes nested in the lambda of the desugared term above it, all the way down to the last expression which is just the body of the nested lambda expression.
The desugaring is quite mechanical, it's defined by the following rewrites, where ; denotes a newline.
do { a <- f ; m } ≡ f >>= \a -> do { m }
do { f ; m } ≡ f >> do { m }
do { m } ≡ m
Both a and b are of type Int while return (a+b) has type Int -> Int which is the last term in the do-notation so it has to be identical to the toplevel signature. Using -XScopedTypeVariables we can manually annotate the subterms:
{-# LANGUAGE ScopedTypeVariables #-}
import Control.Monad.Instances
addStuff :: Int -> Int
addStuff = do
(a :: Int) <- (*2)
(b :: Int) <- (+10)
(return (a+b)) :: Int -> Int
Thanks to bheklilr.
I wrote my own code.
addStuff :: Int -> Int
addStuff = (\r -> r * 2) >>= (\x ->
(\r -> r + 10) >>= (\y ->
return (x + y)))

Convert 2-tuple to 3-tuple Haskell

So I have a list of tuples:
[(1,2),(2,3),(3,4)]
for example. And I perform a calculation on its elements. The result of this should be joined to this tuple, but I don't know how.
[(1,2,103),(2,3,809),(3,4,2034)]
is the format I'm thinking of.
Assuming you have a calculation function like:
calculate :: Int -> Int -> Int
you can do
calculateAll :: [(Int, Int)] -> [(Int, Int, Int)]
calculateAll = map (\(x, y) -> (x, y, calculate x y))
or more generally:
calculateAllWith :: (a -> b -> c) -> [(a, b)] -> [(a, b, c)]
calculateAllWith f = map (\(x, y) -> (x, y, f x y))
A quite straightforward solution:
import Control.Applicative ((<*>))
mapResultOn3rd :: (a -> b -> c) -> [(a,b)] -> [(a,b,c)]
mapResultOn3rd f = map (uncurry (,,) <*> uncurry f)
For example, in ghci:
>>> mapResultOn3rd (:) [(1,[2]), (3,[4,5])]
[(1,[2],[1,2]),(3,[4,5],[3,4,5])]
Use the map function:
calc :: (Int, Int) -> (Int, Int, Int)
calc = error "Implement me"
calcList :: [(Int, Int)] -> [(Int, Int, Int)]
calcList = map calc
You could also use a list comprehension in GHCi:
Prelude> let list = [(1,2),(2,3),(3,4)]
Prelude> [(x,y,x*y) | (x,y) <- list]
[(1,2,2),(2,3,6),(3,4,12)]
http://www.haskell.org/haskellwiki/List_comprehension
Or use the list as a monad:
Prelude> do (x,y) <- list; return (x,y,x*y)
[(1,2,2),(2,3,6),(3,4,12)]
But I prefer the list comprehension :-)

Haskell: Map function with tuples

I have to write a Haskell program that does the following:
Main> dotProduct [(1,3),(2,5),(3,3)] 2
[(2,3),(4,5),(6,3)]
I have to do it both with and without map function.
I already did it without map, but I have no clue to do it with map.
My dotProduct without map function:
dotProduct :: [(Float, Integer)] -> Float -> [(Float, Integer)]
dotProduct [] _ = []
dotProduct [(x,y)] z = [(x*z,y)]
dotProduct ((x,y):xys) z = (x*z,y):dotProduct (xys) z
So I really need help with the map version.
Rather than starting by trying to fit map in somehow, consider how you might simplify and generalize your current function. Starting from this:
dotProduct :: [(Float, Integer)] -> Float -> [(Float, Integer)]
dotProduct [] _ = []
dotProduct [(x,y)] z = [(x*z,y)]
dotProduct ((x,y):xys) z = (x*z,y):dotProduct (xys) z
First, we'll rewrite the second case using the (:) constructor:
dotProduct ((x,y):[]) z = (x*z,y):[]
Expanding the [] in the result using the first case:
dotProduct ((x,y):[]) z = (x*z,y):dotProduct [] z
Comparing this to the third case, we can see that they're identical except for this being specialized for when xys is []. So, we can simply eliminate the second case entirely:
dotProduct :: [(Float, Integer)] -> Float -> [(Float, Integer)]
dotProduct [] _ = []
dotProduct ((x,y):xys) z = (x*z,y):dotProduct (xys) z
Next, generalizing the function. First, we rename it, and let dotProduct call it:
generalized :: [(Float, Integer)] -> Float -> [(Float, Integer)]
generalized [] _ = []
generalized ((x,y):xys) z = (x*z,y):generalized (xys) z
dotProduct :: [(Float, Integer)] -> Float -> [(Float, Integer)]
dotProduct xs z = generalized xs z
First, we parameterize it by the operation, specializing to multiplication for dotProduct:
generalized :: (Float -> Float -> Float) -> [(Float, Integer)] -> Float -> [(Float, Integer)]
generalized _ [] _ = []
generalized f ((x,y):xys) z = (f x z,y):generalized f (xys) z
dotProduct :: [(Float, Integer)] -> Float -> [(Float, Integer)]
dotProduct xs z = generalized (*) xs z
Next, we can observe two things: generalized doesn't depend on arithmetic directly anymore, so it can work on any type; and the only time z is used is as the second argument to f, so we can combine them into a single function argument:
generalized :: (a -> b) -> [(a, c)] -> [(b, c)]
generalized _ [] = []
generalized f ((x,y):xys) = (f x, y):generalized f (xys)
dotProduct :: [(Float, Integer)] -> Float -> [(Float, Integer)]
dotProduct xs z = generalized (* z) xs
Now, we note that f is only used on the first element of a tuple. This sounds useful, so we'll extract that as a separate function:
generalized :: (a -> b) -> [(a, c)] -> [(b, c)]
generalized _ [] = []
generalized f (xy:xys) = onFirst f xy:generalized f (xys)
onFirst :: (a -> b) -> (a, c) -> (b, c)
onFirst f (x, y) = (f x, y)
dotProduct :: [(Float, Integer)] -> Float -> [(Float, Integer)]
dotProduct xs z = generalized (* z) xs
Now we again observe that, in generalized, f is only used with onFirst, so we again combine them into a single function argument:
generalized :: ((a, c) -> (b, c)) -> [(a, c)] -> [(b, c)]
generalized _ [] = []
generalized f (xy:xys) = f xy:generalized f (xys)
dotProduct :: [(Float, Integer)] -> Float -> [(Float, Integer)]
dotProduct xs z = generalized (onFirst (* z)) xs
And once again, we observe that generalized no longer depends on the list containing tuples, so we let it work on any type:
generalized :: (a -> b) -> [a] -> [b]
generalized _ [] = []
generalized f (x:xs) = f x : generalized f xs
Now, compare the code for generalized to this:
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
It also turns out that a slightly more general version of onFirst also exists, so we'll replace both that and generalized with their standard library equivalents:
import Control.Arrow (first)
dotProduct :: [(Float, Integer)] -> Float -> [(Float, Integer)]
dotProduct xs z = map (first (* z)) xs
dotProduct xs z = map (\(x,y) -> (x*z,y)) xs
The (\(x,y) -> (x*z,y)) part is a function which takes a pair and returns a new pair that's like the old one, except its first component is multiplied by z. The map function takes a function and applies it to each element in a list. So if we pass the (\(x,y) -> (x*z,y)) function to map, it will apply that function to every element in xs.
Although are you sure your first one is correct? The dot product operation is usually defined so that it takes two vectors, multiplies corresponding component and then sums it all together. Like this:
dotProduct xs ys = sum $ zipWith (*) xs ys
EEVIAC already posted the answer, so I'll just explain how to come up with it yourself. As you probably know, map has the type signature (a -> b) -> [a] -> [b]. Now, dotProduct has the type [(Float, Integer)] -> Float -> [(Float, Integer)] and you'll call map somewhere in there, so it has to look something like this:
dotProduct theList z = map (??? z) theList
where ??? is a function of type Float -> (Float, Integer) -> (Float, Integer) - this follows immediately from the type signature of map and from the fact that we pass z to the function, which we have to do, simply because there's no other place to use it in.
The thing with map and higher order functions in general is that you have to keep in mind what the higher order function does and "simply" supply it with the correct function. As map applies a given function to all elements in the list, your function only needs to work with one element, and you can forget all about the list - map will take care of it.

Resources