I am a beginner to functional programming and Haskell as a programming language. After given an input of numbers from the command line I want to put those numbers into a list, then pass that list as a parameter to calculate its sum. Here's what I am working on:
import Data.List
iotxt :: IO ()
main :: IO ()
l1 = []
iotxt = do a <- getLine
-- read in numbers that are not equal to -1
insert (read a) l1
if (not ((read a) == -1.0))
then iotxt
else do return ()
main = do
putStrLn("Enter a number [-1 to quit]")
iotxt
-- size of the list
print(length [l1])
-- sum
But when I attempt to place the values inside the list I get this error:
Couldn't match expected type `IO a0' with actual type `[a1]'
In the return type of a call of `insert'
In a stmt of a 'do' block: insert (read a) l1
In the expression:
do { a <- getLine;
insert (read a) l1;
if (not ((read a) == - 1.0)) then iotxt else do { return () } }
There are multiple things wrong with you're code.
Starting from the bottom up, first, length [l1] doesn't make sense. Any [ ] with only one item in between is just that: a list with a single item, so the length will always be 1. You certainly mean length l1 here, i.e. length of the list l1, not length of the list ᴄᴏɴᴛᴀɪɴɪɴɢ only l1.
Next, you have this iotxt and try to make it modify the "global variable" l1. You can't do that, Haskell does not have any such thing as mutable global variables – for good reasons; global mutable state is considered evil even in imperative languages. Haskell kind of has local variables, through IORefs, but using those without good reason is frowned upon. You don't really need them for something like this here.
The correct thing to do is to scrap this global l1 binding, forget about mutating variables. Which brings us to the question of how to pass on the information acquired in iotxt. Well, the obvious functional thing to do is, returning it. We need to make that explicit in the type (which is again a good thing, so we actually know how to use the function):
ioTxt :: IO [Int]
Such a function can then nicely be used in main:
main :: IO ()
main = do
putStrLn "Enter a number [-1 to quit]"
l1 <- ioTxt
print $ length l1
You see: almost the same as your approach, but with proper explicit introduction of l1 where you need it, rather than somewhere completely different.
What's left to do is implementing ioTxt. This now also needs a local l1 variable since we have scrapped the global one. And when you implement a loop as such a recursive call, you need to pass an updated version of it to each instantiation. The recursion itself should be done on a locally-defined function.
ioTxt :: IO [Int]
ioTxT = go [] -- Start with empty list. `go` is a widespread name for such simple "loop functions".
where go l1 = do
a <- getLine
let x = read a :: Int
case x of
(-1) -> return l1
_ -> go (insert x l1)
In the last line, note that insert does not modify the list l1, it rather creates a new one that equals the old one except for having the new element in it. And then passes that to the next loop-call, so effectively you get an updated list for each recursive call.
Also note that you probably shouldn't use insert here: that's specifically for placing the new element at the right position in an ordered list. If you just want to accumulate the values in some way, you can simply use
_ -> go $ x : l1
In haskell, there are no variables, everything is immutable. So you shouldn't define l1 and change its value later, which doesn't work.
Instead you should think how to write iotxt properly and let it collect elements and pass the input list back to your main.
In your iotxt, you can think about these two situations:
if the input is -1, then we can just pass an empty list [] back, wrap it inside the IO by return []
if the input is not -1, we can first store this value somewhere, say result. After that, we should call iotxt recursively and let this inner iotxt handle the rest of the inputs. Finally, we will get return value rest, then we just simply put result and rest together.
Moreover, you can think of IO a like some program (which might have side effects like reading from input or writing to output) that returns a value of type a. According to the definition of your iotxt, which is a program that reads input until meeting a -1 and gives you the list in return, the type signature for iotxt should be IO [Float].
There's a length [l1] in your code, which constructs a list with only one element(i.e. l1) and thus length [l1] will always return 1. Instead of doing this, you can say length l1, which calculates the length of l1.
Finally, you don't need to group function arguments by parenthese, just simply say f x if you want to call f with x.
I've modified your code a little bit, hope it can give you some help.
import Data.List
-- iotxt reads from stdin, yields [Float]
-- stop reading when "-1" is read
iotxt :: IO [Float]
main :: IO ()
iotxt = do
a <- getLine
-- read in numbers that are not equal to -1
let result = (read a) :: Float
if (not (result == -1.0))
then do
-- read rest of the list from stdin
rest <- iotxt
-- put head & tail together
return $ result:rest
else do return []
main = do
putStrLn("Enter a number [-1 to quit]")
l1 <- iotxt
-- size of the list
print $ length l1
-- sum
print $ sum l1
Related
Consider the two following variations:
myReadListTailRecursive :: IO [String]
myReadListTailRecursive = go []
where
go :: [String] -> IO [String]
go l = do {
inp <- getLine;
if (inp == "") then
return l;
else go (inp:l);
}
myReadListOrdinary :: IO [String]
myReadListOrdinary = do
inp <- getLine
if inp == "" then
return []
else
do
moreInps <- myReadListOrdinary
return (inp:moreInps)
In ordinary programming languages, one would know that the tail recursive variant is a better choice.
However, going through this answer, it is apparent that haskell's implementation of recursion is not similar to that of using the recursion stack repeatedly.
But because in this case the program in question involves actions, and a strict monad, I am not sure if the same reasoning applies. In fact, I think in the IO case, the tail recursive form is indeed better. I am not sure how to correctly reason about this.
EDIT: David Young pointed out that the outermost call here is to (>>=). Even in that case, does one of these styles have an advantage over the other?
FWIW, I'd go for existing monadic combinators and focus on readability/consiseness. Using unfoldM :: Monad m => m (Maybe a) -> m [a]:
import Control.Monad (liftM, mfilter)
import Control.Monad.Loops (unfoldM)
myReadListTailRecursive :: IO [String]
myReadListTailRecursive = unfoldM go
where
go :: IO (Maybe String)
go = do
line <- getLine
return $ case line of
"" -> Nothing
s -> Just s
Or using MonadPlus instance of Maybe, with mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a:
myReadListTailRecursive :: IO [String]
myReadListTailRecursive = unfoldM (liftM (mfilter (/= "") . Just) getLine)
Another, more versatile option, might be to use LoopT.
That’s really not how I would write it, but it’s clear enough what you’re doing. (By the way, if you want to be able to efficiently insert arbitrary output from any function in the chain, without using monads, you might try a Data.ByteString.Builder.)
Your first implementation is very similar to a left fold, and your second very similar to a right fold or map. (You might try actually writing them as such!) The second one has several advantages for I/O. One of the most important, for handling input and output, is that it can be interactive.
You’ll notice that the first builds the entire list from the outside in: in order to determine what the first element of the list is, the program needs to compute the entire structure to get to the innermost thunk, which is return l. The program generates the entire data structure first, then starts to process it. That’s useful when you’re reducing a list, because tail-recursive functions and strict left folds are efficient.
With the second, the outermost thunk contains the head and tail of the list, so you can grab the tail, then call the thunk to generate the second list. This can work with infinite lists, and it can produce and return partial results.
Here’s a contrived example: a program that reads in one integer per line and prints the sums so far.
main :: IO ()
main = interact( display . compute 0 . parse . lines )
where parse :: [String] -> [Int]
parse [] = []
parse (x:xs) = (read x):(parse xs)
compute :: Int -> [Int] -> [Int]
compute _ [] = []
compute accum (x:xs) = let accum' = accum + x
in accum':(compute accum' xs)
display = unlines . map show
If you run this interactively, you’ll get something like:
$ 1
1
$ 2
3
$ 3
6
$ 4
10
But you could also write compute tail-recursively, with an accumulating parameter:
main :: IO ()
main = interact( display . compute [] . parse . lines )
where parse :: [String] -> [Int]
parse = map read
compute :: [Int] -> [Int] -> [Int]
compute xs [] = reverse xs
compute [] (y:ys) = compute [y] ys
compute (x:xs) (y:ys) = compute (x+y:x:xs) ys
display = unlines . map show
This is an artificial example, but strict left folds are a common pattern. If, however, you write either compute or parse with an accumulating parameter, this is what you get when you try to run interactively, and hit EOF (control-D on Unix, control-Z on Windows) after the number 4:
$ 1
$ 2
$ 3
$ 4
1
3
6
10
This left-folded version needs to compute the entire data structure before it can read any of it. That can’t ever work on an infinite list (When would you reach the base case? How would you even reverse an infinite list if you did?) and an application that can’t respond to user input until it quits is a deal-breaker.
On the other hand, the tail-recursive version can be strict in its accumulating parameter, and will run more efficiently, especially when it’s not being consumed immediately. It doesn’t need to keep any thunks or context around other than its parameters, and it can even re-use the same stack frame. A strict accumulating function, such as Data.List.foldl', is a great choice whenver you’re reducing a list to a value, not building an eagerly-evaluated list of output. Functions such as sum, product or any can’t return any useful intermediate value. They inherently have to finish the computation first, then return the final result.
I would like to allow a user to build a list from a series of inputs in Haskell.
The getLine function would be called recursively until the stopping case ("Y") is input, at which point the list is returned.
I know the function needs to be in a similar format to below. I am having trouble assigning the correct type signatures - I think I need to include the IO type somewhere.
getList :: [String] -> [String]
getList list = do line <- getLine
if line == "Y"
then return list
else getList (line : list)
So there's a bunch of things that you need to understand. One of them is the IO x type. A value of this type is a computer program that, when later run, will do something and produce a value of type x. So getLine doesn't do anything by itself; it just is a certain sort of program. Same with let p = putStrLn "hello!". I can sequence p into my program multiple times and it will print hello! multiple times, because the IO () is a program, as a value which Haskell happens to be able to talk about and manipulate. If this were TypeScript I would say type IO<x> = { run: () => Promise<x> } and emphatically that type says that the side-effecting action has not been run yet.
So how do we manipulate these values when the value is a program, for example one that fetches the current system time?
The most fundamental way to chain such programs together is to take a program that produces an x (an IO x) and then a Haskell function which takes an x and constructs a program which produces a y (an x -> IO y and combines them together into a resulting program producing a y (an IO y.) This function is called >>= and pronounced "bind". In fact this way is universal, if we add a program which takes any Haskell value of type x and produces a program which does nothing and produces that value (return :: x -> IO x). This allows you to use, for example, the Prelude function fmap f = (>>= return . f) which takes an a -> b and applies it to an IO a to produce an IO b.
So It is so common to say things like getLine >>= \line -> putStrLn (upcase line ++ "!") that we invented do-notation, writing this as
do
line <- getLine
putStrLn (upcase line ++ "!")
Notice that it's the same basic deal; the last line needs to be an IO y for some y.
The last thing you need to know in Haskell is the convention which actually gets these things run. That is that, in your Haskell source code, you are supposed to create an IO () (a program whose value doesn't matter) called Main.main, and the Haskell compiler is supposed to take this program which you described, and give it to you as an executable which you can run whenever you want. As a very special case, the GHCi interpreter will notice if you produce an IO x expression at the top level and will immediately run it for you, but that is very different from how the rest of the language works. For the most part, Haskell says, describe the program and I will give it to you.
Now that you know that Haskell has no magic and the Haskell IO x type just is a static representation of a computer program as a value, rather than something which does side-effecting stuff when you "reduce" it (like it is in other languages), we can turn to your getList. Clearly getList :: IO [String] makes the most sense based on what you said: a program which allows a user to build a list from a series of inputs.
Now to build the internals, you've got the right guess: we've got to start with a getLine and either finish off the list or continue accepting inputs, prepending the line to the list:
getList = do
line <- getLine
if line == 'exit' then return []
else fmap (line:) getList
You've also identified another way to do it, which depends on taking a list of strings and producing a new list:
getList :: IO [String]
getList = fmap reverse (go []) where
go xs = do
x <- getLine
if x == "exit" then return xs
else go (x : xs)
There are probably several other ways to do it.
I am currently learning Haskell and I have a hard time to see What are the common ways to save intermediaries result in Haskell.
For example, let's say that I have a program that take a file, produce some intermediary results and then take some parameters and use the result of the first step to produce something else. Plus, let's say that at the end the user could change the parameters to produce new output but the processing of the first step should not be redone in order to reduce the computation time.
Basically, I just need to temporally save the result of the first step. This would be fairly simple for me in a OO way but because of Haskell purity I don't see a convenient way to solve this.
There are many ways to deal with intermediate results in Haskell. It sounds to me like you would like your main function to look something like this. I will assume you have some function that produces an intermediate result (runFirstStep), a function that prompts for settings (promptForSettings), and a function that uses the intermediate result and the settings to produce a final value (runSecondStep)
main :: IO ()
main = do
-- setup, compute shared value
intermediate <- runFirstStep
-- processing
-- prompt for settings here
settings <- promptForSettings
final <- runSecondStep intermediate settings
-- and done
print final
If you want a more complex control-flow, you could define a separate function, like so:
main :: IO ()
main = do
-- setup, compute shared value
intermediate <- runFirstStep
-- run the second step computation
processLoop intermediate
print final
processLoop :: intermediate -> IO final
processLoop intermediate = do
settings <- promptForSettings
final <- runSecondStep intermediate settings
-- check if user wants to run with different settings
rerun <- do
putStrLn "Run again? [Y/n]"
result <- getStrLn
return (result != "n")
if rerun
then process
else return final
If you are interested in more complex control flows that are impure, there are many ways to store intermediate computations in memory using a variety of techniques. The lowest level and most difficult to get right is to use IORef. Above that, you can use MVar as a way of signalling and locking sections of code based on some shared state, but even that can be tricky to get right. At the highest level, ST and STM let you handle shared state in much more complex ways and are easier to reason about.
An example: You want to read in a bunch of numbers and then compute different sums of powers of those numbers (sums of squares, sums of cubes, etc.)
The first step is to "ignore the IO" - forget for the moment how you are going to get the numbers and the power parameter - and concentrate on the function that does meat of the work - computes the sums of n-th powers of a list of numbers.
powersum :: [Double] -> Int -> Double
powersum xs n = sum $ map (^n) xs
We'll want to compute power sums for various exponents. Again, I would forget about what you are going to do with them later, whether it be print them out, sort them, etc. and write a function which does the computation:
powersums :: [Double] -> [Int] -> [Double]
powersums xs ns = map (powersum xs) ns
Now let's hook it up to the real world. Let's first consider the case when we know the exponents in advance but read the numbers from standard input (all on a single line.)
main = do line <- getLine -- IO
let nums = map read (words line) \
let exponents = [1..10] | - pure code
let sums = powersums nums exponents /
print sums -- IO
Note how our IO sandwiches our pure code - this is very typical of functional programs.
Now suppose you want to also read in the exponents from stdin, and print out the power sums of each read exponent. You could write an imperative-style program like this:
main = do line <- getLine
let nums = map read (words line)
forever $ do exp <- read `fmap` getLine
putStrLn $ show $ powersum nums exp
This illustrates how data (nums in this case) is being stored for use by other parts of the program.
I have the following function:
get :: Chars -> IO Chars
get cs = do
char <- getChar
let (dats, idx) = (curData cs, curIndex cs)
let (x,y:xs) = splitAt idx dats
let replacement = x ++ (ord char) : xs
return $ Chars replacement idx
and I'd like to get a Chars value out of it, not an IO action. I have no idea how to do this, or if it is even possible.
The Chars type is basically just a container:
data Chars = Chars {
curData :: [Int],
curIndex :: Int
-- etc.
}
The specifics aren't that important, I just want to know if there's a way for this function to return a Chars instead of an IO Chars.
If not, how do I pass this as an argument to a function that takes a Chars? I'm kind of new to Haskell I/O, but I don't think I want all of my functions that take Chars as arguments to instead have to take IO Chars as arguments, and then extract and repackage them. It seems unnecessary.
Thanks!
You can't, because that would violate referential transparency.
IO in Haskell is made this way exactly to distinguish between actions whose result and effects may vary depending on the interaction with the environment/user and pure functions whose results are not going to change when you call them with the same input parameters.
In order to pass the result to a pure function taking a Chars in input you have to call your IO action into another IO action, bind the result with the <- operator to a variable and pass it to your pure function. Pseudocode example:
myPureFunction :: Chars -> ...
otherAction :: Chars -> IO ()
otherAction cs = do
myChars <- get cs
let pureResult = myPureFunction myChars
...
If you're new to IO in haskell, you may wish to have a look at the Input and Output chapters in Learn You a Haskell for a Great Good! and Real World Haskell.
There is actually a way to simply get a pure value out of an IO action, but in your case you shouldn't do it, as you're interacting with the environment: the unsafe way is ok only when you can guarantee you're not violating referential transparency.
It's impossible (I lie, there is an extremely unsafe way to cheat your way out of it).
The point is that if any I/O is performed, the behaviour and result of your programme may not depend only on explicit arguments to the used functions, thus that must be declared in the type by having it IO something.
You use the result of an IO a action in a pure function by binding the result in main (or something called from main) and then applying the pure function, binding the result in a let,
cs ::Chars
cs = undefined
main = do
chars <- get cs
let result = pureFunction chars
print result
or, if the function you want to apply to chars has type Chars -> IO b
main = do
chars <- get cs
doSomething chars
I'm trying to spew out randomly generated dice for every roll that the user plays. The user has 3 rolls per turn and he gets to play 5 turns (I haven't implemented this part yet and I would appreciate suggestions).
I'm also wondering how I can display the colors randomly. I have the list of tuples in place, but I reckon I need some function that uses random and that list to match those colors. I'm struggling as to how.
module Main where
import System.IO
import System.Random
import Data.List
diceColor = [("Black",1),("Green",2),("Purple",3),("Red",4),("White",5),("Yellow",6)]
{-
randomList :: (RandomGen g) -> Int -> g -> [Integer]
random 0 _ = []
randomList n generator = r : randomList (n-1) newGenerator
where (r, newGenerator) = randomR (1, 6) generator
-}
rand :: Int -> [Int] -> IO ()
rand n rlst = do
num <- randomRIO (1::Int, 6)
if n == 0
then doSomething rlst
else rand (n-1) (num:rlst)
doSomething x = putStrLn (show (sort x))
main :: IO ()
main = do
--hSetBuffering stdin LineBuffering
putStrLn "roll, keep, score?"
cmd <- getLine
doYahtzee cmd
--rand (read cmd) []
doYahtzee :: String -> IO ()
doYahtzee cmd = do
if cmd == "roll"
then rand 5 []
else do print "You won"
There's really a lot of errors sprinkled throughout this code, which suggests to me that you tried to build the whole thing at once. This is a recipe for disaster; you should be building very small things and testing them often in ghci.
Lecture aside, you might find the following facts interesting (in order of the associated errors in your code):
List is deprecated; you should use Data.List instead.
No let is needed for top-level definitions.
Variable names must begin with a lower case letter.
Class prerequisites are separated from a type by =>.
The top-level module block should mainly have definitions; you should associate every where clause (especially the one near randomList) with a definition by either indenting it enough not to be a new line in the module block or keeping it on the same line as the definition you want it to be associated with.
do introduces a block; those things in the block should be indented equally and more than their context.
doYahtzee is declared and used as if it has three arguments, but seems to be defined as if it only has one.
The read function is used to parse a String. Unless you know what it does, using read to parse a String from another String is probably not what you want to do -- especially on user input.
putStrLn only takes one argument, not four, and that argument has to be a String. However, making a guess at what you wanted here, you might like the (!!) and print functions.
dieRoll doesn't seem to be defined anywhere.
It's possible that there are other errors, as well. Stylistically, I recommend that you check out replicateM, randomRs, and forever. You can use hoogle to search for their names and read more about them; in the future, you can also use it to search for functions you wish existed by their type.