Skip to content

Commit

Permalink
Add Pitch.Hz module for working with musical pitches in Hertz
Browse files Browse the repository at this point in the history
  • Loading branch information
Bernardo Barros committed Jan 31, 2024
1 parent cdc966a commit 9b617ee
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions haskMus.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ library
Pitch.Parser
Pitch.Pitch
Pitch.QuasiQuoter
Pitch.Hz
Rtm.Common
Rtm.Parser
Rtm.QuasiQuoter
Expand Down
33 changes: 33 additions & 0 deletions src/Pitch/Hz.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
module Pitch.Hz where

-- | The Pitch.Hz module provides types and functions to work with musical pitches in terms of semitones and Hertz.

-- `newtype` wrappers for `Semitone` and `Hz` provide type safety.
newtype Semitone = Semitone {unSemitone :: Double} deriving (Show, Eq, Num, Ord)
newtype Hz = Hz {unHz :: Double} deriving (Show, Eq, Num, Ord)

-- Standard pitch (A4) definition in Hertz.
pitchStandard :: Hz
pitchStandard = Hz 440.0

-- Convert a `Semitone` or `Double` representing semitones to `Hz`.
-- Works for both integral and fractional semitones.
semitoneToHz :: Double -> Hz
semitoneToHz n = pitchStandard * Hz (2 ** (n / 12.0))

-- Convert a frequency in `Hz` to its equivalent in semitones relative to `pitchStandard`.
-- Calculated using the logarithm base 2.
hzToDouble :: Hz -> Double
hzToDouble (Hz hz) = 12.0 * logBase 2 (hz / unHz pitchStandard)

-- Use `hzToDouble` to convert Hz to `Semitone`.
hzToSemitone :: Hz -> Semitone
hzToSemitone = Semitone . hzToDouble

-- Directly retrieve the underlying `Double` from a `Semitone`.
semitoneToDouble :: Semitone -> Double
semitoneToDouble (Semitone n) = n

-- Wrap a `Double` as a `Semitone`.
doubleToSemitone :: Double -> Semitone
doubleToSemitone = Semitone

0 comments on commit 9b617ee

Please sign in to comment.