Created
November 5, 2014 03:25
-
-
Save ilyakava/3a632a9df1132526510b to your computer and use it in GitHub Desktop.
Code from a meetup presentation: http://www.meetup.com/N-Languages-in-N-Months-NYC/events/202521322/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Code from a meetup presentation: http://www.meetup.com/N-Languages-in-N-Months-NYC/events/202521322/ | |
-- Implements half adder and full adder circuits | |
-- Installation: `brew install ghc cabal-install` | |
-- Check compilation: `ghc Main.hs` | |
-- Load into repl: | |
-- $ cabal repl` | |
-- Prelude> :l Main.hs | |
module Main where | |
--resolve name clash by doing: | |
import Prelude hiding (and, or) | |
main :: IO () | |
main = undefined | |
--returns nothing, always starts off with main | |
--define a bit | |
--'data' is a keyword, defining two constructors, the symbol High and Low | |
--Bit is now a type, we tried to use it below in a type signature | |
data Bit = High | Low | |
-- a way to show our output | |
deriving (Show) | |
--expression problem - sometimes there is no silver bullet | |
--make a function | |
--take a bit and return two bits, one sum and one carry | |
halfAdder :: Bit -> Bit -> (Bit, Bit) | |
--descriptive naming, whether inside or outside | |
--we want to describe the output from the input | |
--input is a pair, so is output | |
halfAdder inputOne inputTwo = (inputOne `xor` inputTwo, inputOne `and` inputTwo) | |
xor :: Bit -> Bit -> Bit | |
xor High Low = High | |
xor Low High = High | |
xor _ _ = Low | |
and :: Bit -> Bit -> Bit | |
and High High = High | |
and _ _ = Low | |
fullAdder :: Bit -> Bit -> Bit -> (Bit, Bit) | |
--these are lazy, if we wanted to evaluate immediately with bangs `!` | |
fullAdder inputOne inputTwo carryIn = | |
(sumOutputTwo, carryOutput `or` carryOutputTwo) | |
where | |
--need input from one half adder, output of first half adder | |
--'destructure' is used here, with some pattern matching as in the rest of the file | |
(sumOutput, carryOutput) = halfAdder inputOne inputTwo | |
(sumOutputTwo, carryOutputTwo) = halfAdder sumOutput carryIn | |
or :: Bit -> Bit -> Bit | |
or Low Low = Low | |
or _ _ = High |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment