I'm writing an audio program in Haskell using Portaudio. I have a function that generates a list of samples I'd like to play, and I'm trying to play them using the following snippet inside main:
curSamps <- return (chunk 1 (sineWave 440 44100))
forever $ do
Right numSampsAvail <- getStreamWriteAvailable paStream
Right NoError <- writeStream paStream curSamps numSampsAvail
curSamps <- return (drop numSampsAvail curSamps)
sineWave is a function I've created to generate an infinite list of Int16 samples of a sinewave at a specified frequency and sample rate.
When I debug this code, by replacing the audio output code with a putStrLn, it prints all 0s, which is the first sample from the function.
How can I iterate over this list with the audio output functions? I don't think I can use recursion or a map.
Edit: Code copying mistake
Use recursion:
play [] = return ()
play curSamps = do Right numSampsAvail <- getStreamWriteAvailable paStream
Right NoError <- writeStream paStream curSamps numSamps
play (drop numSampsAvail curSamps)
main = do ...
play (chunk 1 (sineWave 440 44100))
...
Consider using map's monadic cousins mapM/forM.
Using the same API functions one can do this:
let playSamples curSamps = do
Right numSampsAvail <- getStreamWriteAvailable paStream
Right NoError <- writeStream paStream curSamps numSampsAvail
playSamples (drop numSampsAvail curSamps)
playSamples (chunk 1 (sineWave 440 44100))
I'm not familiar with the Portaudio API, so it might provide a more convenient, higher-level way of doing what you're trying to achieve.
Related
I have question related Haskell language.i need to store bunch of characters in 2D array.How can i store it??I have characters in 10 X 10 format in text file and i want to store it in 2D character array in haskell language.Please help me as soon as possible..thank you..
Here is the code which i tried and in this code i am trying to store value of x in the list named listofchar::
module TreasureFile where
import System.IO
main = do
hdl <- openFile "map.txt" ReadMode
readbychar hdl
readbychar hdl = do
t <- hIsEOF hdl
if t
then return()
else do
let listofchar=[]
x <- hGetChar hdl
if x =='\n'
then putChar '!'--return()
else listofchar x
readbychar hdl
Try this:
import System.IO
main = do
textContents <- readFile "map.txt"
let map = format textContents
print $ map
format text = lines text
Lets step through this program:
First, readFile reads us the file and binds the contents to textContents.
Next we format the contents by splitting the list every time we encounter a newline delimiter and then remove the eventually remaining empty strings.
Done! Now we can do whatever we want with our "map".
A small note on the side:
It will seem strange that our map will be displayed like this:
["aaaaaaaaaa","bbbbbbbbbbb",..] -- doesn't look like 2D map
which is just syntatic sugar for:
[['a','a','a',..],['b','b','b',..],..] -- looks more like a map now
I am unsure on how to use setPosition (Parsec library). Here is an extremely simple piece of code which should read the first 3 characters of the second line of a text.
import Text.ParserCombinators.Parsec
content = ["This is the first line",
"and this is the second one",
"not to talk about the third one"]
txt = unlines content
main = parseTest myPar txt
myPar = getPosition >>= \oldPos ->
let newPos = setSourceLine oldPos 2 in
setPosition newPos >>
count 3 anyChar
Still, the output is "Thi" and not "and" as I would excpect... I feel I am missing somethning very simple, but alas, I don't know what; can you help me?
The setPosition function changes what position Parsec reports for errors, but does not affect where in the stream of tokens the parsing actually is. It is used as a primitive for back-ends that need to do fancy things: preprocessors that must report positions in other files, parsers that operate on streams of non-Char tokens, and so forth.
I'm trying to learn Haskell to get used to functional programming languages. I've decided to try a few problems at interviewstreet to start out. I'm having trouble reading from stdin and doing io in general with haskell's lazy io.
Most of the problems have data coming from stdin in the following form:
n
data line 1
data line 2
data line 3
...
data line n
where n is the number of following lines coming from stdin and the next lines are the data.
How do I run my program on each of the n lines one at a time and return the solution to stdout?
I know the stdin input won't be very large but I'm asking about evaluating each line one at a time pretending the input is larger than what can fit in memory just to learn how to use haskell.
You can use interact, in conjunction with lines to process data from stdin one line at a time. Here's an example program that uses interact to access stdin, lines to split the data on each newline, a list comprehension to apply the function perLine to each line of the input, and unlines to put the output from perLine back together again.
main = interact processInput
processInput input = unlines [perLine line | line <- lines input]
perLine line = reverse line -- do whatever you want to 'line' here!
You don't need to worry about the size of the data you're getting over stdin; Haskell's laziness ensures that you only keep the parts you're actually working on in memory at any time.
EDIT: if you still want to work on only the first n lines, you can use the take function in the above example, like this:
processInput input = unlines [perLine line | line <- take 10 (lines input)]
This will terminate the program after the first ten lines have been read and processed.
You can also use a simple recursion:
getMultipleLines :: Int -> IO [String]
getMultipleLines n
| n <= 0 = return []
| otherwise = do
x <- getLine
xs <- getMultipleLines (n-1)
return (x:xs)
And then use it in your main:
main :: IO ()
main = do
line <- getLine
let numLines = read line :: Int
inputs <- getMultipleLines numLines
I am using a toolchain to convert markdown to HMTL5 using Pandoc for insertion into WordPress's visual editor as HTML content.
When it comes to inserting images, WordPress puts what is called a shortcode of the form
[caption id="attachment_100" align="aligncenter" width="300" caption="This is an image caption"]
into the HTML text. This is not really markdown but is so interpreted by Pandoc which translates each " ... " pair into a <q> ... </q> pair for HTML output. This does not work correctly in WordPress.
I need to prevent the conversion of the " ... " but only those which occur within the well-defined [caption ... ] square brackets which are exclusively put in by WordPress and cannot be confused with other content that I put in.
I do not know enough about the Pandoc API or Haskell to write an inline paseser/filter to exempt this text fragment from Pandoc processing. The advice I have received on the pandoc mailing list has gone above my head so far, given my lack of acquaintance with Pandoc and Haskell.
I thought of writing a Perl filter but have been strongly dissuaded from using regexps for very good reason.
I am asking here to find out if there is a robust way to make the reverse substitution from <q> ... </q> tags to " ... " only for the text within the [caption ... ] block after it has been run through pandoc, as a post-processing step.
Can someone please suggest how I might go about this?
Many thanks.
Did you want something like this?
import Data.List
import System.IO
main = do
inh <- openFile "input.txt" ReadMode
outh <- openFile "output.txt" WriteMode
str <- hGetContents inh
hPutStrLn outh (outsideCaption str)
hClose inh
hClose outh
outsideCaption::String->String
outsideCaption [] = []
outsideCaption str#(x:xs)
| isPrefixOf "[caption" str = insideCaption str
| otherwise = x:outsideCaption xs
insideCaption::String->String
insideCaption [] = []
insideCaption (']':xs) = ']':outsideCaption xs
insideCaption str#(x:xs)
| (isPrefixOf "<q>" str) = '\"':insideCaption (drop 3 str)
| (isPrefixOf "</q>" str) = '\"':insideCaption (drop 4 str)
| otherwise = x :insideCaption xs
This piece of code reads a file named "input.txt", does the substitution you described and prints the result to "output.txt".
replacing the current main with:
main = interact outsideCaption
makes it read from stdin to stdout, example:
[rothesay]Ygfijj: echo "testing <q> [caption<q></q>]" | ./test
testing <q> [caption""]
I want to do a popen() / python's subprocess.communicate from Haskell - start a program, give it stdin, and get its stdout/stderr. What's the most direct / Haskellish way to do this?
Pick either MissingH's System.Cmd.Utils and the standard library's System.Process. They're easy to use, with both high-level convenience functions (which you simply throw strings at and get strings back, possibly lazily) and low-level plumbing functions (which actually give you handles, like most popen functions in other languages/frameworks).
import System.Process
main = do
let cmd = "mail"
args = ["root#localhost", "-s", "does this act like popen?"]
input = ["Hello, world!"]
(rc, out, err) <- readProcessWithExitCode cmd args input
putStrLn $ "mail exited: " ++ show rc
mapM_ putStrLn $ map ("out: " ++) $ lines out
mapM_ putStrLn $ map ("err: " ++) $ lines err
The other option could be to use shelly package