Haskell No instance for Show - haskell

Here is my code:
type Niveles = (Int, Int, Int)
type Persona = (String, Niveles)
type Pocion = (String, [(String, Int, [Efectos])])
type Ingredientes = [(String, Int, [Efectos])]
type Efectos = Niveles -> Niveles
aplicar3 f (a,b,c) = (f a, f b, f c)
invertir3 (a,b,c) = (c,b,a)
fst3 (a,_,_) = a
snd3 (_,b,_) = b
trd3 (_,_,c) = c
personas = [("Harry",(11, 5, 4)), ("Ron",(6,4,6)), ("Hermione",(8,12,2)), ("Draco",(7,9,6))]
f1 (ns,nc,nf) = (ns+1,nc+2,nf+3)
f2 = aplicar3 (max 7)
f3 (ns,nc,nf)
| ns >= 8 = (ns,nc,nf+5)
| otherwise = (ns,nc,nf-3)
misPociones :: [Pocion]
misPociones = [
("Felix Felices",[("Escarabajos Machacados",52,[f1,f2]),("Ojo de Tigre Sucio",2,[f3])]),
("Multijugos",[("Cuerno de Bicornio en Polvo",10, [invertir3, (\(a,b,c) -> (a,a,c))]),("Sanguijuela hormonal",54,[(aplicar3 (*2)), (\(a,b,c) -> (a,a,c)) ])]),
("Flores de Bach",[("Orquidea Salvaje",8,[f3]), ("Rosita",1,[f1])])]
efectosDePocion pocion = map trd3 (elementos pocion)
elementos :: Pocion -> Ingredientes
elementos (_, ingredientes) = ingredientes
I have a problem in the last piece of code, when I try to use the function "elementos":
elementos ("Felix Felices",[("Escarabajos Machacados",52,[f1,f2]),("Ojo de Tigre Sucio",2,[f3])])
I've got an error message:
<interactive>:311:1:
No instance for (Show ((Int, Int, Int) -> (Int, Int, Int)))
arising from a use of `print'
Possible fix:
add an instance declaration for
(Show ((Int, Int, Int) -> (Int, Int, Int)))
In a stmt of an interactive GHCi command: print it
Can someone explain this to me? How can I fix it?

In short, the function evaluates correctly - the problem is caused by evaluating it in ghci.
Your function call returns a value of type Ingredientes which is a type synonym for [(String, Int, [Efectos])]. ghci tries to print the returned value to the console, so it tries to call show on it. But Efectos is a type synonym for a function. ghci tells you that it doesn't know how to display a function, because it's not a member of the typeclass Show: No instance for (Show ((Int, Int, Int) -> (Int, Int, Int))).
It probably shouldn't concern you - you'd get a similar error by evaluating any function in ghci.

Add to your .hs file the following code
instance Show (a -> b) where
show a= "funcion"
Now ghci will be able to print "funcion" (function)
Good luck!

Related

How do I add an Applicative context to a type expected by Lens' MyDataType?

I have a function generalized over a function func to be applied on MyDataType1 and another MyDataType1 like this
setThis :: (Functor f0, Applicative f0) => Lens' MyDataType1 (f0 Float) -> Float -> MyDataType1 -> MyDataType1 -> MyDataType1
setThis func toThis dataType1 dataType2 = dataType2 & func %~ (\a -> (+) <$> a <*> delta
where baseStat = dataType1 ^. func -- baseStat has type Maybe Float
delta = (\a -> toThis * a) <$> baseStat -- also have type Maybe Float
where MyDataType1 is (when used with print. Every numeric value is a Float)
data MyDataType1 = MyDataType1 { _name = Just "First"
, _length = Just 5.5
, _dmsTypes = Just
( DMS { _i = Just 1.9
, _j = Nothing
, _k = Just 95.9
}
)
}
The function setThis given a default record function like length, a constant Float, a data set to get base value from and a data set to modify, sets _length to a number that's a sum of the original value and the value from the other set multiplied by some constant.
It works just as I expect when given function length.
What I want to do is have the exact same behavior when given a function like (dmsTypes . _j) as in
setThis (dmsTypes . _Just . _j) 0.3 (someY) (someY) -- someY :: MyDataType1
Although GHC throws this error if I do just that
Could not deduce (Applicative f) arising from a use of ‘_Just’
from the context: Functor f
bound by a type expected by the context:
Lens' MyDataType1 (Maybe Float)
Possible fix:
add (Applicative f) to the context of
a type expected by the context:
Lens' MyDataType1 (Maybe Float)
And while it seems like GHC knows exactly what I should do, I don't know how to do it.
Since the thing func points at might not exist, it should be a traversal (any number of focused values) rather than a lens (exactly one focused value).
The part of setThis that uses a setter (i.e., (%~)) remains the same, but the getter part (i.e., (^.)) should instead use a fold, with (^?). In that case, dataType1 ^? func will have two layers of Maybe, one from (^?) and one from func (in what is currently f0), that you'll probably want to flatten with join.
baseState = join (dataType1 ^? func)
Now f0 must be Maybe.
setThis :: Traversal' MyDataType1 (Maybe Float) -> ...

Create a SEXP vector using fromList

I'm trying to use the Data.Vector.SEXP module. I am a newbie in Haskell.
Here is what I do and get:
> let x = Data.Vector.SEXP.fromList [2,3]
<interactive>:35:5:
Non type-variable argument in the constraint: Num (ElemRep s ty)
(Use FlexibleContexts to permit this)
When checking that ‘x’ has the inferred type
x :: forall s (ty :: Foreign.R.Type.SEXPTYPE).
(ty
Foreign.R.Constraints.:∈ '['Foreign.R.Type.Char,
'Foreign.R.Type.Logical, 'Foreign.R.Type.Int,
'Foreign.R.Type.Real, 'Foreign.R.Type.Complex,
'Foreign.R.Type.String, 'Foreign.R.Type.Vector,
'Foreign.R.Type.Expr, 'Foreign.R.Type.WeakRef,
'Foreign.R.Type.Raw],
Num (ElemRep s ty), Storable (ElemRep s ty),
Data.Singletons.SingI ty) =>
Data.Vector.SEXP.Vector s ty (ElemRep s ty)
I am lost. I'd like to have an example of a SEXP vector created from a list.
Try doing this instead:
> let x = Data.Vector.SEXP.fromList ([2,3] :: [Int])
The problem is that in Haskell, number literals are overloaded, so [2,3] has type Num a => [a] instead of [Int].
Another way taken from the HaskllR unittests is to specific a data type
import qualified Foreign.R as R
import qualified Data.Vector.SEXP as V
idVec :: V.Vector s 'R.Real Double -> V.Vector s 'R.Real Double
idVec = id
Then:
let v = idVec $ V.fromList [-1.9,-0.1,-2.9]

Haskell type error: Could not deduce (Show a) arising from a use of `show' from the context (Num a)

I am configuring xmonad, and since I have to start a couple of dzen instances, I decided that it could be better to use a function that takes the parameters for x and y position, width, height and text align:
-- mydzen.hs
import Data.List
-- | Return a string that launches dzen with the given configuration.
myDzen :: Num a => a -> a -> a -> Char -> String -> String
myDzen y x w ta e =
intercalate " "
[ "dzen2"
, "-x" , show x
, "-w" , show w
, "-y" , show y
, "-h" , myHeight
, "-fn" , quote myFont
, "-bg" , quote myDBGColor
, "-fg" , quote myFFGColor
, "-ta" , [ta]
, "-e" , quote e
]
quote :: String -> String
quote x = "'" x "'"
-- dummy values
myHeigth = "20"
myFont = "bitstream"
myDBGColor = "#ffffff"
myFFGColor = "#000000"
Could not deduce (Show a) arising from a use of `show'
from the context (Num a)
bound by the type signature for
myDzen :: Num a => a -> a -> a -> Char -> String -> String
at mydzen.hs:(5,1)-(17,13)
Possible fix:
add (Show a) to the context of
the type signature for
myDzen :: Num a => a -> a -> a -> Char -> String -> String
In the expression: show x
In the second argument of `intercalate', namely
`["dzen2", "-x", show x, "-w", ....]'
In the expression:
intercalate " " ["dzen2", "-x", show x, "-w", ....]
Obviously, deleting the signature, or changing Num a for Show a solves the issue, but I can't understand why. The 'arguments' x, w and y are supposed to be almost any kind of numbers (100, 550.2, 1366 * 0.7 ecc).
I'm new to haskell and until now I haven't been able to (clearly) understand the error or find what's wrong.
Previously, Show and Eq were superclasses of Num and the code would compile.
In the new GHC, from version 7.4, this has changed, now Num does not depend on Show and Eq, so you need to add them to signatures.
The reason is separation of concerns - there are numeric types with no sensible equality and show function (computable reals, rings of functions).
Not all numbers are showable (standard types like Int or Integer are, but you could have defined your own type; how would compiler know?) You’re using show x in your function — therefore, a must belong to Show typeclass. You can change your signature to myDzen :: (Num a, Show a) => a -> a -> a -> Char -> String -> String and get rid of the error.
show is not part of the Num type class — to be able to use it, you have to add Show constraint alongside the Num one:
myDzen :: (Num a, Show a) => a -> a -> a -> Char -> String -> String

Data initialization and data members change in Haskell

I'm new to Haskell and I cannot figure out how you declare a "Data" type and how you can initialize a variable with that type. I'd also like to know how can I change the values of certain members of that variable. For exaple :
data Memory a = A
{ cameFrom :: Maybe Direction
, lastVal :: val
, visited :: [Direction]
}
Direction is a Data type that contains N,S,E,W
val is a Type int
init :: Int -> a
init n = ((Nothing) n []) gives me the following error:
The function `Nothing' is applied to two arguments,
but its type `Maybe a0' has none
In the expression: ((Nothing) n [])
In an equation for `init': init n = ((Nothing) n [])
how can I fix this ?
UPDATE: That did it, thank you very much, but now i have another issue
move :: val -> [Direction] -> Memory -> Direction
move s cs m | s < m.lastVal = m.cameFrom
| ...
this gives me the following error:
Couldn't match expected type `Int' with actual type `a0 -> c0'
Expected type: val
Actual type: a0 -> c0
In the second argument of `(<)', namely `m . lastVal'
In the expression: s < m . lastVal
UPDATE 2: Again, that helped me a lot, thank you very much
Also, I have another question (sorry for being such a bother)
How do I adress only an element of a type
For example if I have
Type Cell = (Int, Int)
Type Direction = (Cell, Int)
how do I proceed if I want to compare a Cell variable with the Cell element of a Direction variable?
As to the update. The syntax
m.lastVal
and
m.cameFrom
is not what you want. Instead
move s cs m | s < lastVal m = cameFrom m
accessors are just functions, so used in prefix form. The . in Haskell is used for namespace resolution (which is not path dependent) and for function composition
(.) :: (b -> c) -> (a -> b) -> a -> c
(.) f g x = f (g x)
To initialise:
init :: Int -> Memory Int
init n = A {cameFrom = Nothing, lastVal = n, visited = []}
To change values: strictly speaking you don't change values, you return another different value, like this:
toGetBackTo :: Direction -> Memory a -> Memory a
toGetBackTo dir memory = memory {cameFrom = Just dir, visited = dir : visited memory}

What to do with “Inferred type is less polymorphic than expected”?

I need the Numeric.FAD library, albeit still being completely puzzled by existential types.
This is the code:
error_diffs :: [Double] -> NetworkState [(Int, Int, Double)]
error_diffs desired_outputs = do diff_error <- (diff_op $ error' $ map FAD.lift desired_outputs)::(NetworkState ([FAD.Dual tag Double] -> FAD.Dual tag Double))
weights <- link_weights
let diffs = FAD.grad (diff_error::([FAD.Dual tag a] -> FAD.Dual tag b)) weights
links <- link_list
return $ zipWith (\link diff ->
(linkFrom link, linkTo link, diff)
) links diffs
error' runs in a Reader monad, ran by diff_op, which in turn generates an anonymous function to take the current NetworkState and the differential inputs from FAD.grad and stuffs them into the Reader.
Haskell confuses me with the following:
Inferred type is less polymorphic than expected
Quantified type variable `tag' is mentioned in the environment:
diff_error :: [FAD.Dual tag Double] -> FAD.Dual tag Double
(bound at Operations.hs:100:33)
In the first argument of `FAD.grad', namely
`(diff_error :: [FAD.Dual tag a] -> FAD.Dual tag b)'
In the expression:
FAD.grad (diff_error :: [FAD.Dual tag a] -> FAD.Dual tag b) weights
In the definition of `diffs':
diffs = FAD.grad
(diff_error :: [FAD.Dual tag a] -> FAD.Dual tag b) weights
this code gives the same error as you get:
test :: Int
test =
(res :: Num a => a)
where
res = 5
The compiler figured that res is always of type Int and is bothered that for some reason you think res is polymorphic.
this code, however, works fine:
test :: Int
test =
res
where
res :: Num a => a
res = 5
here too, res is defined as polymorphic but only ever used as Int. the compiler is only bothered when you type nested expressions this way. in this case res could be reused and maybe one of those uses will not use it as Int, in contrast to when you type a nested expression, which cannot be reused by itself.
If I write,
bigNumber :: (Num a) => a
bigNumber = product [1..100]
then when bigNumber :: Int is evaluated,
it's evaluating (product :: [Int] -> Int) [(1 :: Int) .. (100 :: Int)],
and when bigNumber :: Integer is evaluated,
it's evaluating (product :: [Integer] -> Integer) [(1 :: Integer) .. (100 :: Integer)].
Nothing is shared between the two.
error_diffs has a single type, that is: [Double] -> NetworkState [(Int, Int, Double)]. It must evaluate in exactly one way.
However, what you have inside:
... :: NetworkState ([FAD.Dual tag Double] -> FAD.Dual tag Double)
can be evaluated in different ways, depending on what tag is.
See the problem?

Resources