Last active
December 31, 2023 01:01
-
-
Save yamasushi/70a83af1a4ac8c9f2f6acf22e6dca94a to your computer and use it in GitHub Desktop.
binary number with a decimal point
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
module Bindec2 where | |
import Debug.Trace | |
{- | |
# binary number with a "decimal" point | |
Compilers 2nd ed. | |
Exercise 5.2.4 (p.317) | |
Exercise 5.2.5 (p.317) | |
Exercise 5.5.6 (p.352) | |
Compilers 1st ed. | |
Exercise 5.8 (p.337) | |
https://gist.github.com/yamasushi/70a83af1a4ac8c9f2f6acf22e6dca94a | |
------ | |
S -> L . L | L | |
L -> L B | B | |
B -> 0 | 1 | |
S -> L F { S.val =L.val + F.val } | |
F -> . L { F.val=L.val/(2^L.k) } | |
F -> ε { F.val=0 } | |
L -> B { R.ik =1 , R.ival=B.val } | |
R { L.val = R.val , L.k = R.k } | |
R -> B { R1.ik = R.ik + 1 , R1.ival = 2*R.ival + B.val } | |
R1 { R.val = R1.val , R.k = R1.k } | |
R -> ε { R.val = R.ival , R.k=R.ik } | |
B -> 0 { B.val =0 } | |
B -> 1 { B.val =1 } | |
-} | |
bindec2 :: String -> Float | |
bindec2 xs = snd.s$xs | |
s :: String -> (String,Float) | |
s xs = let (xs0,_,val0)= (l xs) in | |
let (xs1,val1)=(f xs0) in | |
( xs1 , val0+val1 ) | |
f :: String->(String,Float) | |
f ('.':xs) = let (xs0,k,val)= (l xs) in | |
(xs0,val/(2^k)) | |
f xs = (xs,0) {-ipsilon-} | |
l :: String->(String,Int,Float) | |
l xs = let (xs0,bit) = (b xs) in | |
(r xs0 1 bit) | |
r :: String->Int->Float -> (String,Int,Float) | |
r [] ik ival = ([],ik,ival) {-ipsilon-} | |
r xs@(bit:_) ik ival | |
| bit=='0' || bit=='1' = | |
let (xs0,bval)= (b xs) in | |
let | |
ik0 = ik+1 | |
ival0 = ival*2 + bval in | |
(r xs0 ik0 ival0) | |
| otherwise = (xs,ik,ival) {-ipsilon-} | |
b :: String -> (String,Float) | |
b ('0':xs) = (xs,0.0) | |
b ('1':xs) = (xs,1.0) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment