I am having trouble with this simple code as it is giving me an error stating that there is an incorrect Indention.
opMe x y op = if op =="+" let x+y
main=do
op = "+"
x = 8
y = 10
print(opMe (x, y, op))
The return I am looking for is 18.
The return I have received is Incorrect Indention.
Lots of problems here. Let's fix them one by one:
opMe x y op = if op =="+" let x+y
main=do
op = "+"
x = 8
y = 10
print(opMe (x, y, op))
q58566673.hs:3:1: error:
parse error (possibly incorrect indentation or mismatched brackets)
|
3 | main=do
| ^
The problem here isn't actually indentation. It's that your if statement doesn't have a then or else, so the parser is expecting it to continue, rather than you starting a new declaration. It looks like you used let where you meant to use then, so let's change that. Also, else is mandatory in Haskell. Since you didn't define any other operations yet, I'll use undefined for now, which will let your program compile, but crash if you ever end up there.
opMe x y op = if op =="+" then x+y else undefined
main=do
op = "+"
x = 8
y = 10
print(opMe (x, y, op))
q58566673.hs:3:1: error: parse error on input ‘main’
|
3 | main=do
| ^^^^
Still doesn't work. Ironically, now the problem is indentation, but the new error message no longer mentions that as a possibility. Specifically, the problem is the leading space before opMe. Let's remove that.
opMe x y op = if op =="+" then x+y else undefined
main=do
op = "+"
x = 8
y = 10
print(opMe (x, y, op))
q58566673.hs:4:6: error:
parse error on input ‘=’
Perhaps you need a 'let' in a 'do' block?
e.g. 'let x = 5' instead of 'x = 5'
|
4 | op = "+"
| ^
Here, GHC's suggestion is correct. You need to use let to declare variables in a do block.
opMe x y op = if op =="+" then x+y else undefined
main=do
let op = "+"
let x = 8
let y = 10
print(opMe (x, y, op))
q58566673.hs:5:11: error:
• Ambiguous type variable ‘a0’ arising from the literal ‘8’
prevents the constraint ‘(Num a0)’ from being solved.
Relevant bindings include x :: a0 (bound at q58566673.hs:5:7)
Probable fix: use a type annotation to specify what ‘a0’ should be.
These potential instances exist:
instance Num Integer -- Defined in ‘GHC.Num’
instance Num Double -- Defined in ‘GHC.Float’
instance Num Float -- Defined in ‘GHC.Float’
...plus two others
...plus one instance involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the expression: 8
In an equation for ‘x’: x = 8
In the expression:
do let op = "+"
let x = 8
let y = 10
print (opMe (x, y, op))
|
5 | let x = 8
| ^
q58566673.hs:6:11: error:
• Ambiguous type variable ‘b0’ arising from the literal ‘10’
prevents the constraint ‘(Num b0)’ from being solved.
Relevant bindings include y :: b0 (bound at q58566673.hs:6:7)
Probable fix: use a type annotation to specify what ‘b0’ should be.
These potential instances exist:
instance Num Integer -- Defined in ‘GHC.Num’
instance Num Double -- Defined in ‘GHC.Float’
instance Num Float -- Defined in ‘GHC.Float’
...plus two others
...plus one instance involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the expression: 10
In an equation for ‘y’: y = 10
In the expression:
do let op = "+"
let x = 8
let y = 10
print (opMe (x, y, op))
|
6 | let y = 10
| ^^
q58566673.hs:7:3: error:
• No instance for (Show
((a0, b0, [Char]) -> [Char] -> (a0, b0, [Char])))
arising from a use of ‘print’
(maybe you haven't applied a function to enough arguments?)
• In a stmt of a 'do' block: print (opMe (x, y, op))
In the expression:
do let op = "+"
let x = 8
let y = 10
print (opMe (x, y, op))
In an equation for ‘main’:
main
= do let op = ...
let x = ...
let y = ...
....
|
7 | print(opMe (x, y, op))
| ^^^^^^^^^^^^^^^^^^^^^^
q58566673.hs:7:9: error:
• No instance for (Num (a0, b0, [Char]))
arising from a use of ‘opMe’
• In the first argument of ‘print’, namely ‘(opMe (x, y, op))’
In a stmt of a 'do' block: print (opMe (x, y, op))
In the expression:
do let op = "+"
let x = 8
let y = 10
print (opMe (x, y, op))
|
7 | print(opMe (x, y, op))
| ^^^^^^^^^^^^^^^
That's a spectacularly unhelpful set of error messages. The reason these errors are so unhelpful is that they're a type mismatch error, but you didn't specify a type for opMe, so GHC inferred one that was more polymorphic (and thus gives more complicated error messages) than necessary. Let's add a type signature to get a better error message.
opMe :: Integer -> Integer -> String -> Integer
opMe x y op = if op =="+" then x+y else undefined
main=do
let op = "+"
let x = 8
let y = 10
print(opMe (x, y, op))
q58566673.hs:8:14: error:
• Couldn't match expected type ‘Integer’
with actual type ‘(Integer, Integer, [Char])’
• In the first argument of ‘opMe’, namely ‘(x, y, op)’
In the first argument of ‘print’, namely ‘(opMe (x, y, op))’
In a stmt of a 'do' block: print (opMe (x, y, op))
|
8 | print(opMe (x, y, op))
| ^^^^^^^^^^
Much more clear. The problem here is that you defined your function curried (i.e., opMe x y op), but then called it as if it were uncurried (i.e., opMe (x, y, op)). To fix it, pick one or the other and stick to it. Since currying is idiomatic in Haskell, let's go with it:
opMe :: Integer -> Integer -> String -> Integer
opMe x y op = if op =="+" then x+y else undefined
main=do
let op = "+"
let x = 8
let y = 10
print(opMe x y op)
18
And we're done! It works now.
Related
How do i define a Binary instance for Data.Number.BigFloat?
I've defined an instance for LongDouble by writing:
instance Binary LongDouble where
put d = put (decodeFloat d)
get = do
x <- get
y <- get
return $! encodeFloat x y
However trying the following doesn't work:
instance Binary (BigFloat e) where
put d = put (decodeFloat d )
get = do
x <- get
y <- get
return $! encodeFloat x y
GHC gives this error message:
/home/usr/Documents/src/Lib.hs:27:18: error:
• No instance for (Epsilon e) arising from a use of ‘decodeFloat’
Possible fix:
add (Epsilon e) to the context of the instance declaration
• In the first argument of ‘put’, namely ‘(decodeFloat d)’
In the expression: put (decodeFloat d)
In an equation for ‘put’: put d = put (decodeFloat d)
|
27 | put d = put (decodeFloat d )
| ^^^^^^^^^^^^^
/home/usr/Documents/src/Lib.hs:31:19: error:
• No instance for (Epsilon e) arising from a use of ‘encodeFloat’
Possible fix:
add (Epsilon e) to the context of the instance declaration
• In the second argument of ‘($!)’, namely ‘encodeFloat x y’
In a stmt of a 'do' block: return $! encodeFloat x y
In the expression:
do x <- get
y <- get
return $! encodeFloat x y
|
31 | return $! encodeFloat x y
If I provide a specific type for e, such as Prec500, i get this message :
• Illegal instance declaration for ‘Binary (BigFloat Prec500)’
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use FlexibleInstances if you want to disable this.)
• In the instance declaration for ‘Binary (BigFloat Prec500)’
And using FlexibleInstances compiles, but doesn't result in correctly encoded numbers.
The following also compiles but doesn't encode correctly either:
instance Epsilon e => Binary (BigFloat e) where
put d = put (decodeFloat d )
get = do
x <- get
y <- get
return $! encodeFloat x y
This BigFloat seems to be not super-well-done. The problem lies here:
> floatDigits (0 :: BigFloat Prec500)
-9223372036854775808
(The correct answer should be 500.) I admit I don't fully understand why that is happening; but from the source, the way floatDigits is computed is by taking the log of the precision -- but log is a thing that happens on Doubles and Double doesn't have enough precision to represent 1e-500. So that method of computing the digit count seems doomed from the start.
Why do I say I don't fully understand? Well, I see the following in the source:
floatDigits (BF m _) =
floor $ logBase base $ recip $ fromRational $ precision m
From my reading, fromRational should produce 0 :: Double. But if that were true, the final value would be 0, not minBound:
> floor $ logBase 10 $ recip $ (0 :: Double) :: Int
0
So perhaps there is some dodgy rewriting going on or something.
Anyway, a proper implementation of this type should work differently -- e.g. by having a more informative class than Epsilon that can report the precision as a base and exponent. (Another possible idea would be to have floatRadix return recip precision and floatDigits return 1, but that has some oddities around what should happen if the precision is not the reciprocal of a whole number.)
I am trying to import a custom module into main using ghci and I am getting this error I don't really understand.
Main.hs
module Main where
import Newton (my_sqrt)
main = my_sqrt 25
Newton.hs
module Newton where
deriv f x = (f(x + dx) - f(x))/dx
where dx = 0.0001
newton f = until satis improve
where satis y = abs(f y) < eps
eps = 0.0001
improve y = y - (f y/deriv f y)
my_sqrt x = newton f x
where f y = y^2 - x
my_cubrt x = newton f x
where f y = y**3 - x
I try to load these into ghci using
:l Main.hs
I get this error
Main.hs:9:8: error:
• No instance for (Fractional (IO t0))
arising from a use of ‘my_sqrt’
• In the expression: my_sqrt 25
In an equation for ‘main’: main = my_sqrt 25
Main.hs:9:16: error:
• No instance for (Num (IO t0)) arising from the literal ‘25’
• In the first argument of ‘my_sqrt’, namely ‘25’
In the expression: my_sqrt 25
In an equation for ‘main’: main = my_sqrt 25
Failed, modules loaded: Newton.
How do I solve this issue?
The type of main is required to be IO ().
The type of sqrt 25 is, apparently, Fractional t => t (it is really advisable to always include type signatures for your top-level entities in the program; you miss those).
To reconcile the two you can define e.g.
main :: IO ()
main = print (sqrt 25)
because the type of print is print :: Show a => a -> IO ().
While learning Haskell I found something which puzzled me.
I don't understand why this code is valid:
Prelude> [y | y <- "a", y <- ["a"]]
["a"]
I tried to change to an explicit [Char] and got the same result (which makes sense):
Prelude> [y | y <- ['a'], y <- ["a"]]
["a"]
Surprisingly this is valid too :
Prelude> [y | y <- "a", y <- [["a"]]]
[["a"]]
[EDIT]
the error given is not related to the same fact :
This on the contrary is invalid as I would expect:
Prelude> [y | y <- 'a', y <- ['a']]
<interactive>:12:11: error:
* Couldn't match expected type `[t0]' with actual type `Char'
* In the expression: 'a'
In a stmt of a list comprehension: y <- 'a'
In the expression: [y | y <- 'a', y <- ['a']]
[y | y <- 'a'] is invalid because 'a' is not a list.
[/EDIT]
I thought it was some usual mess caused by String vs Char but definitely not:
Prelude> [y | y <- [1], y <- [[2]]]
[[2]]
For the record I'm using GHCi version 8.2.2 and Arch Linux.
Turn on warnings! You should see that the first y is being shadowed by the second one.
It is somehow similar to
let y = True
in let y = "a"
in y
where the first definition is overshadowed, as if it were
let _ = True
in let y = "a"
in y
or even, removing the shadowed binding,
let y = "a"
in y
Similarly, a list comprehension such as
[y | y <- "a", y <- ["a"]]
evaluates to the same result as
[y | _ <- "a", y <- ["a"]]
-- or, if you prefer
[y | x <- "a", y <- ["a"]]
Note that, unlike the let above, in list comprehensions we can not simply remove the overshadowed binding y <- .... For instance,
[y | y <- [1,2], y <- [3,4]]
produces [3,4,3,4], unlike [y | y <- [3,4]].
Here you can see the produced warning for each examples :
Prelude> :set -Wall
Prelude> [y | y <- "a", y <- ["a"]]
<interactive>:41:6: warning: [-Wunused-matches]
Defined but not used: `y'
<interactive>:41:16: warning: [-Wname-shadowing]
This binding for `y' shadows the existing binding
bound at <interactive>:41:6
["a"]
Prelude> [y | x <- "a", y <- ["a"]]
<interactive>:47:6: warning: [-Wunused-matches]
Defined but not used: `x'
["a"]
-- no warning here
Prelude> [y | _ <- "a", y <- ["a"]]
["a"]
Prelude> [y | y <- [1,2] , y <- [3,4]]
<interactive>:49:1: warning: [-Wtype-defaults]
* Defaulting the following constraints to type `Integer'
(Show a0) arising from a use of `print' at <interactive>:49:1-29
(Num a0) arising from a use of `it' at <interactive>:49:1-29
* In a stmt of an interactive GHCi command: print it
<interactive>:49:6: warning: [-Wunused-matches]
Defined but not used: `y'
<interactive>:49:12: warning: [-Wtype-defaults]
* Defaulting the following constraint to type `Integer'
Num t0 arising from the literal `1'
* In the expression: 1
In the expression: [1, 2]
In a stmt of a list comprehension: y <- [1, 2]
<interactive>:49:12: warning: [-Wtype-defaults]
* Defaulting the following constraint to type `Integer'
Num t0 arising from the literal `1'
* In the expression: 1
In the expression: [1, 2]
In a stmt of a list comprehension: y <- [1, 2]
<interactive>:49:19: warning: [-Wname-shadowing]
This binding for `y' shadows the existing binding
bound at <interactive>:49:6
[3,4,3,4]
Im trying to solve this kind of equatin: e^x + sqrt(x) = d, when d is known. It does not have analytic solution so I use variation of binary search to solve it:
helper x = exp x + sqrt x
ex2 c0 c1 x
| abs (h0 - h1) < 10 ^^ (-6) = c0
| hm < x = ex2 m c1 x
| hm >= x = ex2 c0 m x
where h0 = helper c0
h1 = helper c1
m = c0 + (c1 - c0)/2
hm = helper m
This works fine from ghci (c0 and c1 is min and max value for search) but i have problems reading argument x from stdio:
main = do
seed <- getLine
let output = show ex2 0 6 (read seed :: Floating) -- Result is somewhere between helper(0) and helper(6)
in putStrLn output
This breaks my code. It does not compile or load in ghci. I got this error message:
ex2.hs:14:46:
Expecting one more argument to ‘Floating’
Expected a type, but ‘Floating’ has kind ‘* -> Constraint’
In an expression type signature: Floating
In the fourth argument of ‘show’, namely ‘(read seed :: Floating)’
In the expression: show ex2 0 6 (read seed :: Floating)
Can someone explain what it means and how to fix my main function?
There was parentheses missing in let.. line:
Another error: show (ex2 ... (read seed :: Double)) requires parentheses. – chi
I'm reading about lazy evaluations in haskell and have a question. For example we have following computations:
Prelude> let x = 1 + 1 :: Int
Prelude> let y = (x,x)
And after getting value of x:
Prelude> :sprint x
x = _
It's unevaluated. Ok, now let's get value of y:
Prelude> :sprint y
y = (_,_)
It is unevaluated too, because y depends on x and it's unevaluated. Now let's try the same example but without ::Int:
Prelude> let x = 1 + 1
Prelude> let y = (x, x)
Prelude> :sprint y
y = _
Why y value is _ instead (_, _) when we're trying without ::Int?
I see that they have different types:
Prelude> let x = 1 + 1
Prelude> :t x
x :: Num a => a
Prelude> let x = 1 + 1 :: Int
Prelude> :t x
x :: Int
But why values of y depends on it?
Thank you.
What is happening is that when you've specified x to have the type Num a => a, the compiler can't possibly know which instance of Num to use when performing 1 + 1. What it does instead is use defaulting. GHC defines default types for certain typeclasses so that when there's no possible way to determine what concrete type to use it can still give meaningful results without raising errors. So when you see
> let x :: Num a => a
| x = 1 + 1
> x
2
> :sprint x
x = _
This is because GHCi chooses Integer as its default type for Num, but when it performs this operation it doesn't store the result in x's memory location, since there isn't a way to know if that is even the correct answer. This is why you see x = _ from :sprint, it hasn't actually evaluated x :: Num a => a, it's evaluated x :: Integer. You can even mess with this default yourself:
> newtype MyInt = MyInt Int deriving (Eq)
>
> instance Show MyInt where
| show (MyInt i) = show i
> instance Num MyInt where
| (MyInt x) + (MyInt y) = MyInt (x - y)
| fromInteger = MyInt . fromInteger
>
> default (MyInt)
> x
0
So now we've said that 1 + 1 = 0! Keep in mind that you will probably never have a use for this functionality of GHC, but it's good to know about.