Haskell TidbitshaskellTidbits
Contents
Full Source Code For All Examples
Arduino Serial IOOverviewThe Arduino is a popular electronics prototyping platform. It is easy to interface to a computer via a real or emulated (Through USB) serial connection. This write-up details how to communicate with the Arduino in Haskell. Pre-requisites
Send a simple commandimport System.Serial import IO serialCommand :: String -> IO () serialCommand comm = do h <- openSerial "/dev/ttyUSB0" B9600 8 One NoParity Software hPutStr h comm Servo and LED DemoQuick demo of running a servo motor and LED from Haskell using serialMonitor.hs. H turns on the light, L turns it off, the numbers 0-9 are the step to take (0-180) by 20 degree increments. The Arduino sends back a status after each command, saying either the state of the light, or the degree of the servo. Video of serialMonitor.hs program running: HDBC MySQL ConnectivityOverviewHDBC-mysql is a way to talk to mysql using Haskell. Like alot of things in Hackage, there isn't alot of demo code, so here is how I've been using it. Besides the initial connection it provides the same functions/types as the rest of HDBC. Database SetupRequires the following MySQL setup: CREATE DATABASE hdbcTest; GRANT ALL ON hdbcTest.* TO hdbc@'%' IDENTIFIED BY 'hdbc'; use hdbcTest; create table test ( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), value varchar(255) ); /var/run/mysqld/mysqld.sock Change as needed. Haskell ConnectionSimple connection and test: import Control.Monad
import Database.HDBC
import Database.HDBC.MySQL
main = do
conn <- connectMySQL defaultMySQLConnectInfo {
mysqlHost = "localhost",
mysqlPort = 3306,
mysqlUnixSocket = "/var/run/mysqld/mysqld.sock",
mysqlDatabase = "hdbcTest",
mysqlUser = "hdbc",
mysqlPassword = "hdbc"
}
rows <- quickQuery' conn "SELECT 1 + 1" []
forM_ rows $ row -> putStrLn $ show row
Something a little more complicated. Grab the count of entries, insert that count, and then spit out all the values. After the connection is established (ie the bottom of the last example). rows <- quickQuery' conn "SELECT count(*) from test" []
run conn ("insert into test (value) values" ++
countString rows) []
rows <- quickQuery' conn "SELECT value from test" []
forM_ rows $ row -> putStrLn $ sqlValue row
That increase each time the code is ran. Collatz ConjectureOverviewThe Collatz Conjecture is based on sequences from the following formulas: n/2 for even n 3*n + 1 for odd n Collatz Sequence CodeCode to generate sequences and find the lengths of the sequences: test :: Int -> Int
test x | even x = x `div` 2
| otherwise = 3*x + 1
collatz :: Int -> [Int]
collatz 1 = [1]
collatz x = x : collatz (test x)
numCollatz = map (length . collatz) [1..]
Output CodeGenerates a table that gnuplot can handle. format x y = show x ++ "t" ++ show y table x = unlines (zipWith format [1..] (take x numCollatz)) main = writeFile "collatz.dat" (table 100000) Media
![]() XOR Character Arrays
|
Posts
Source Code
