Show for IO types - haskell

I have a data type which contains an IORef as an important element. This means there is not a clean way to make it a member of the show type class. This is not too bad as I have a print function in the IO monad for this type. But it is annoying in GHCi in that every time I return one of these thing as a result I get an error stating that it cannot be shown.
Is there a way to get GHCi, which operates in the IO monad anyway, to use an IO action to show a result? If not, would there be any negative consequences to writing show a = unsafePerformIO $ print a?

Have you considered adding to your .ghci file something like:
instance (Show a) => Show (IORef a) where
show a = show (unsafePerformIO (readIORef a))
It isn't safe at all, but if this is just for your personal use perhaps that is OK.
For more general use the previously given answers look good to me. That is, either define a static "I can't show this" message:
instance Show (IORef a) where
show _ = "<ioref>"
This would give something like:
> runFunc
MyStruct <ioref> 4 "string val"
Or use a custom function. I suggest making a class and lifting all the Show instances:
class ShowIO a where
showIO :: a -> IO String
instance Show a => ShowIO a where
showIO = return . show
instance ShowIO a => ShowIO (IORef a) where
showIO a = readIORef a >>= showIO
Giving the output (untested, this is just hand-written):
> myFunc >>= showIO
MyStruct "My String in an IORef" 4 "string val"

ghci has three cases for return values:
Show a => a: Just run show and print it
Show a => IO a: Execute the action, run show and print
IO (): print nothing
So usually, if you type an IO action, it get's executed and the result gets printed if it's not (). Let's try it:
ghci>15
15
ghci>'a' : 'b' : 'c' : []
"abc"
ghci>putStrLn "Hello, world!"
Hello, world!
ghci>putStrLn "Hello, world!" >> return 42
Hello, world!
42
ghci>
If you want to print something different, the best way is probably to write a custom function and stick it in front of each line you want to see:
myShowFun :: ... -> IO String
ghci> myShowFun $ ...
foobar

Related

Why do I get Parse error on input`:: here

I am trying to make a guess the number game.
`
main :: IO()
checkGuess :: (Integral a) => a -> Bool
checkGuess b = if b == 9 then return True
main = do
print "Guess the number?"
guess <- getLine
checkGuess guess
but I get parse error on input '::' at the function checkGuess
There are several things that are wrong here:
you do not define the function directly after you wrote the signature of the function. You thus should first write the signature, and then write its binding, strictly speaking this is not an error as #chi says, but it is nevertheless strongly recommended;
In Haskell indentation matters: entering and leaving an indentation level says that you start or end a code block, for example for a where clause;
your checkGuess is supposed to return a Bool, but with return True, you make it a Monad m => m Bool;
in Haskell an if ... then ... else ... without an else does not exist. That is logical since a function should always return something;
getLine has as type IO String, so guess has type String, not Int, Integer, so you can not use guess directly to compare with a number; and
as #Krantz pointed out, the print here should probably be a putStrLn, since otherwise we print a string literal, not the string content.
In general it looks like you are writing an imperative program in a (pure) function language. A quick fix is the following:
checkGuess :: (Eq a, Num a) => a -> Bool
checkGuess = (9 ==)
main :: IO()
main = do
putStrLn "Guess the number?"
guess <- readLn :: IO Int
print (checkGuess guess)

How can I get this currying experiment to behave as expected?

I am writing a currying experiment to get a feel for how multiple statements in haskell are chained together to work one after another.
Here is what I got so far
testCurry :: IO ()
testCurry =
(\b ->
(\_ -> putStrLn b)
((\a ->
putStrLn a
) (show 2))
) (show 3)
testCurryExpected :: IO ()
testCurryExpected = do {
a <- return (show 2);
putStrLn a;
b <- return (show 3);
putStrLn b;
}
main :: IO ()
main =
putStrLn "expected: " >>
testCurryExpected >>
putStrLn "given: " >>
testCurry
I know it works if I do it this way:
testCurry :: IO ()
testCurry =
(\b ->
(\next -> next >> putStrLn b)
((\a ->
putStrLn a
) (show 2))
) (show 3)
testCurryExpected :: IO ()
testCurryExpected = do {
a <- return (show 2);
putStrLn a;
b <- return (show 3);
putStrLn b;
}
main :: IO ()
main =
putStrLn "expected: " >>
testCurryExpected >>
putStrLn "given: " >>
testCurry
But I don't know how to simulate the ">>"(then) behavior only using functions.
I know a >> b is defined in terms of a >>= \_ -> b, but I am not sure how >>= is defined in terms of IO a >>= IO b but don't know how to translate this into raw function composition.
Can somebody please help me get this experiment to work?
In short, I want to know if there is a way to do this without >> or >>= operators nor wrapping these operators.
(\a -> \b -> a >> b)(putStrLn "one")(putStrLn "two")
Note: For the sake of concept, I restrict myself to using anonymous functions of at most one argument.
Edit: I found a good-enough solution by creating my own Free representation of putStrLn called Free_PutStrLn that is free of interpretation; using Lists to construct the operation chain, then evaluate it myself later.
data Free_PutStrLn = Free_PutStrLn String deriving Show
eval :: [Free_PutStrLn] -> IO ()
eval a =
foldl (\a -> \b ->
let deconstruct (Free_PutStrLn str) = str in
a >> putStrLn (deconstruct b)
) (return ()) a
testCurry :: [Free_PutStrLn]
testCurry =
(\a ->
[Free_PutStrLn a] ++
((\b ->
[Free_PutStrLn b]
) (show 3))
)(show 2)
main =
putStrLn (show testCurry) >>
eval (testCurry)
JavaScript proof of concept:
// | suspends an object within a function context.
// | first argument is the object to suspend.
// | second argument is the function object into which to feed the suspended
// | argument(first).
// | third argument is where to feed the result of the first argument feeded into
// | second argument. use a => a as identity.
const pure = obj => fn => f => f(fn(obj));
// | the experiment
pure({'console': {
'log': str => new function log() {
this.str = str;
}
}})(free =>
pure(str => () => console.log(str))
(putStrLn =>
pure("hello")(a =>
[free.console.log(a)].concat (
pure("world")(b =>
[free.console.log(b)]
)(a => a))
)((result =>
pure(logObj => logObj.str)
(deconstruct =>
result.map(str => putStrLn(deconstruct(str)))
)(result =>
result.forEach(f => f())
)
)
)
)(a => a)
)(a => a)
But I don't know how to simulate the >> (then) behavior only using functions.
Well, you can't! >> is (in this case) about ordering side-effects. A Haskell function can never have a side effect†. Side effects can only happen in monadic actions, and can be thus ordered by monadic combinators including >>, but without a Monad‡ constraint the notion of “do this and also that” simply doesn't make any sense in Haskell. A Haskell function is not executed, it's merely a mathematical transformation whose result you may evaluate. That result may itself be an actual action with type e.g. IO (), and such an action can be executed and/or monadically chained with other actions. But this is actually somewhat orthogonal to the evaluation of the function that yielded this action.
So that's the answer: “How can I get this currying experiment to behave as expected?” You can't, you need to use one of the monadic combinators instead (or do notation, which is just syntactic sugar for the same).
To also tackle this question from a bit of a different angle: you do not “need monads” to express sequencing of side effects. I might for instance define a type that “specifies side-effects” by generating e.g. Python code which when executed has these effects:
newtype Effect = Effect { pythons :: [String] }
Here, you could then sequence effects by simply concatenating the instruction lists. Again though, this sequencing would not be accomplished by any kind of currying exercise but by boring list concatenation. The preferable interface for this is the monoid class:
import Data.Monoid
instance Monoid Effect where
mempty = Effect []
mappend (Effect e₀) (Effect e₁) = Effect $ e₀ ++ e₁
And then you could simply do:
hello :: Effect
hello = Effect ["print('hello')"] <> Effect ["print('world')"]
(<> is just a shorthand synonym for mappend. You could as well define a custom operator, say # instead to chain those actions, but if there's a standard class that supports some operation it's usually a good idea to employ that!)
Ok, perfectly fine sequencing, no monadic operators required.
But very clearly, just evaluating hello would not cause anything to be printed: it would merely give you some other source code. You'd actually need to feed these instructions to a Python interpreter to accomplish the side-effects.And in principle that's no different with the IO type: evaluating an IO action also never causes any side-effects, only linking it to main (or to the GHCi repl) does. How many lambdas you wrap the subexpressions in is completely irrelevant for this, because side-effect occurance has nothing to do with whether a function gets called anywhere! It only has to do with how the actions get linked to an actual “executor”, be that a Python interpreter or Haskell's own main.
If you now wonder why it has to be those whacky monads if the simpler Monoid also does the trick... the problem with Effect is that it has no such thing as a return value. You can perfectly well generate “pure output” actions this way that simply execute a predetermined Python program, but you can never get back any values from Python this way to use within Haskell to decide what should happen next. This is what monads allow you to do.
†Yes, never. Haskell does not include something called unsafePerformIO. Anybody who claims otherwise in the comments shall suffer nuclear retaliation.
‡To be precise, the weaker Applicative is sufficient.

Language.Haskell.Interpreter: is this the right tool for the job at hand?

I have a little toy semantics for natural language, with words like:
ran :: String -> Bool
ran = (`elem` ["Bart", "Homer", "Marge"])
and:
bart :: String
bart = "Bart"
So for example, I can have (ran bart) :: Bool, and so on.
I want to write a parser which, for example takes the string "Bart ran" and returns True. I'd probably use Parsec for this.
However, the problem is being able to call functions via strings. E.g. getting from "ran" to the function ran. For this, I thought Language.Haskell.Interpreter's interpret function might be appropriate.
So my questions are:
Is this a sensible way to do what I want to do?
If so, why doesn't the following work, entered into GHCi, given a module called Grammar.hs in the same directory with ran defined as above:
let a = runInterpreter $ do
loadModules ["Grammar"]
setImports ["Prelude"]
interpret "ran" (as :: String -> Bool)
let b = do
x <- a
return $ x <*> pure "John"
b
I get the error:
"Left (WontCompile [GhcError {errMsg = "<interactive>:2:1:\n Not in scope: \8216ran\8217\n Perhaps you meant \8216tan\8217 (imported from Prelude)"}])"
which suggests that the import isn't working, and indeed, if I try something similar with a Prelude function, everything works.
Why do I get the following type error (among many others) if I try to compile the same code as in Q2, (minus the let):
No instance for MonadIO m0 arising from a use of runInterpreter
As for #2, you need to add "Grammar" to the setImports list as well:
runInterpreter $ do
loadModules ["HintDefs"]
setImports ["Prelude", "HintDefs"]
interpret "ran" (as :: String -> Bool)
As for #3, it is because runInterpreter is monomorphic in the choice of monad to run it in:
runInterpreter :: (MonadIO m, MonadMask m)
=> InterpreterT m a
-> m (Either InterpreterError a)
So you'll need to choose a particular m by running it in e.g. IO:
main :: IO ()
main = do
ran <- runInterpreter $ do
loadModules ["HintDefs"]
setImports ["Prelude", "HintDefs"]
interpret "ran" (as :: String -> Bool)
print $ ran <*> pure "John"
Now, as for #1, I am not convinced you need something as stupidly powerful as HInt here. You could just maintain a dictionary of String -> Bool functions keyed by a String key, something simple like a Map String (String -> Bool), and then use that to look up ran etc.

a Show instance for undefined

Can anything be done to define a Show instance for an undefined value? Maybe some GHC extensions exist? I want something like this:
> print (1,undefined)
(1,"undefined")
According to the Haskell 2010 report, chapter 9, evaluating undefined should always cause an error:
-- It is expected that compilers will recognize this and insert error
-- messages that are more appropriate to the context in which undefined
-- appears.
undefined :: a
undefined = error "Prelude.undefined"
Since printing a value includes evaluating it, this will always give an error.
The bottom value (of which undefined is one flavor) is a value that is never constructed and hence can't be observed. This implies that you can't print it either. This value can't be compared to null from other languages, which usually can be observed and even checked against.
It is useful to think of undefined as well as error "blah" and all other bottoms as equivalent to results of infinite loops. The result of an infinite loop is never constructed and hence can't be observed.
More conceptually: The "undefined" is not a value like 'X'. The 'X' value has type Char. What type does "undefined" have? The symbol "undefined" is polymorphic, it can have any type (any type of kind *).
Type classes like "Show t" dispatch on the type t. So different type can and do have different show functions that display them. Which function gets your "undefined" depends on the type.
In GHCI most polymorphic types are defaulted to () so it can run the command. One can make a show function for a new type that does not look at the value:
Prelude> data Test = Test
Prelude> instance Show Test where show x = "I did not look at x"
Prelude> show Test
"I did not look at x"
Prelude> show (undefined :: Test)
"I did not look at x"
But as you can see this avoids the error with undefined by never examining the value at all. So this is a bit useless.
You could make your own type class and printing machinery that runs in IO and catches errors and does sort of what you want:
import Control.Exception
perr s = do x <- try (evaluate (show s)) :: IO (Either SomeException String)
return (either show id x))
The above translates errors into the error's string form:
Prelude Control.Exception> perr True
"True"
Prelude Control.Exception> perr (undefined :: Bool)
"Prelude.undefined"
Note: A better 'perr' needs to force the whole String instead of just the WHNF.
Even though (as the others already pointed out) you can't specify a Show instance for undefined, you may be able to put together a workaround by using catch as in the following code:
import qualified Control.Exception as C
import System.IO.Unsafe (unsafePerformIO)
showCatch :: (Show a) => a -> IO String
showCatch = showCatch' "undefined"
showCatch' :: (Show a) => String -> a -> IO String
showCatch' undef x = C.catch (C.evaluate (show x)) showUndefined
where
showUndefined :: C.ErrorCall -> IO String
showUndefined _ = return undef
unsafeShowCatch :: (Show a) => a -> String
unsafeShowCatch x = unsafePerformIO (showCatch x)
But this example will only work for simple expressions:
*Main> let v1 = showCatch 1
v1 :: IO String
*Main> let v2 = showCatch $ if True then undefined else 0
v2 :: IO String
*Main> v1
"1"
*Main> v2
"undefined"
*Main> let v3 = unsafeShowCatch 1
v3 :: String
*Main> let v4 = unsafeShowCatch $ undefined
v4 :: String
*Main> v3
"1"
*Main> v4
"undefined"
It won't work for calls like
showCatch (1,undefined)

Haskell Input Return Tuple

i wonder can a IO() function return tuple because i would like to get these out of this function as input for another function.
investinput :: IO()->([Char], Int)
investinput = do
putStrLn "Enter Username : "
username <- getLine
putStrLn "Enter Invest Amount : "
tempamount <- getLine
let amount = show tempamount
return (username, amount)
Please help.
Thanks.
IO in Haskell doesn't work like IO in the languages you're used to. All functions in Haskell must be pure: that is, if a function f is called with the argument x, there must be no difference between calling it once, twice, or a hundred times. Consider what this means for IO, though. Naïvely, getLine should have the type getLine :: String, or perhaps getLine :: () -> String. (() is the unit type, whose only value is (); it's sort of like a void type in a C-like language, but there is a single value of it.) But this would mean that every time you wrote getLine, it would have to return the same string, which is not what you want. This is the purpose of the IO type: to encapsulate actions. These actions are distinct from functions; they represent impure computation (though they themselves are pure). A value of type IO a represents an action which, when executed, returns a value of type a. Thus, getLine has type getLine :: IO String: every time the action is evaluated, a String is produced (by reading from the user). Similarly, putStr has type putStr :: String -> IO (); it is a function which takes a string and returns an action which, when run, returns no useful information… but, as a side effect, prints something to the screen.
You are attempting to write a function of type IO () -> ([Char], Int). This would be a function which took as input an action and returned a tuple, which is not what you want. You want an IO (String, Int)—an action which, when run, produces a tuple consisting of a string (which is a synonym for [Char]) and an integer. You're almost there with your current code, too! This is what you'll need instead:
investinput :: IO (String, Int)
investinput = do
putStrLn "Enter Username : "
username <- getLine
putStrLn "Enter Invest Amount : "
tempamount <- getLine
let amount = read tempamount
return (username, amount)
Notice that I've only made two changes (and removed a blank line). First, I've changed the type of the function, like I said above. Second, I changed show into read. The show function has the type Show a => a -> String: it is a function which takes anything which can be shown and produces a string representing it. You wanted read, which has the type Read a => String -> a: given a string, it parses it and returns some readable value.
The other thing you asked about is returning a tuple (String, Int) instead of an action IO (String, Int). There is no pure way to do this; in other words, there is no pure function IO a -> a. Why is this? Because IO a represents an impure action which depends on the real world. If we had such a function impossibleRunIO :: IO a -> a, then we would want it to be the case that impossibleRunIO getLine == impossibleRunIO getLine, since the function must be pure. But this is useless, as we would want impossibleRunIO to be able to actually interact with the real world! Thus, this pure function is impossible. Everything that enters IO can never leave. This is what return does: it is a function with, in this case1, the type return :: a -> IO a, which enables you to place pure values into IO. For any x, return x is an action which, when run, always produces x. This is why you have to end your do block with the return: username is a pure value you extracted from an action, and as such is only visible within the do block. You need to lift it into IO before the outside world can see it. The same is true of amount/tempamount.
And just for completeness's sake: there is some overarching theory behind this which ties it together. But it's not necessary at all for beginning Haskell programming. What I would recommend doing is structuring most of your code as pure functions which fold, spindle, and mutilate your data. Then construct a thin (as thin as possible) IO front layer which interacts with said functions. You'll be surprised how little IO you need!
1: It actually has a more general type, but that's not relevant for the moment.
Yeah, you're almost there but I think you want the signature:
investinput :: IO ([Char], Int)
... then from the calling function you can do something like:
main = do
(username, amount) <- investinput
....
I think you want to read tempamount rather than show though.
An IO function that produces a tuple would have type IO (a, b), in this case:
investinput :: IO ([Char], Int)
A signature of IO () -> ([Char], Int) would mean that the function takes a parameter of type IO () and produces a tuple from that, which is not what you want.
Generally there are no restrictions on the types an IO function (or a function in a different monad) can return, you can chose the types however you like.
The answer to your question about returning (String, Int) rather than IO (String, Int) is simple: you can't. Once you're in IO you're stuck there. That's part of what it means when people say that Haskell is a "pure" language.
What you want to do is similar to what you're already doing here with getLine. The type of getLine is IO String. When you write username <- getLine, you're in effect taking the String out of the IO String, but this is only possible because you're inside the do expression.
You can do exactly the same kind of thing with investinput as with getLine. Here's an example of how you could use investinput in your main function:
main = do
(name, amount) <- investinput
putStrLn $ name ++ " invested $" ++ show amount ++ "."
Since you mention liftM in a comment, here's a full working version that does the same thing using liftM and the reverse bind operator (=<<) instead of do notation:
import Control.Monad (liftM)
investinput :: IO (String, Int)
investinput = do
putStrLn "Enter Username : "
username <- getLine
putStrLn "Enter Invest Amount : "
amount <- liftM read getLine -- We can also use liftM to get rid of tempamount.
return (username, amount)
summary :: (String, Int) -> String
summary (name, amount) = name ++ " invested $" ++ show amount ++ "."
main = putStrLn =<< liftM summary investinput
This shows how you could use investinput with "another function which expects a tuple".

Resources