Last active
December 31, 2023 01:02
-
-
Save yamasushi/a1aa7b14b1afa678512f3a1378303d49 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 Bindec1 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/a1aa7b14b1afa678512f3a1378303d49 | |
S -> L . L | L | |
L -> L B | B | |
B -> 0 | 1 | |
------ | |
S -> { L.side=0 } | |
L {F.ival=L.val} F { S.val=F.val } | |
F -> . { L.side=1 } | |
L { F.val=F.ival + L.val } | |
F -> ε { F.val=F.ival } | |
L -> B { R.side = L.side | |
R.ival = case L.side of | |
0 -> B.val | |
1 -> B.val/2 | |
R.ik = 1} | |
R { L.val=R.val , L.k=R.k} | |
R -> B { R1.side = R.side | |
R1.ik = R.k + 1 | |
R1.ival = case R.side of | |
0 -> R.ival*2 + B.val | |
1 -> R.ival + B.val/(2^(R.k+1)) | |
} | |
R1 { R.val = R1.val ,R.k = R1.k} | |
R -> ε { R.val = R.ival } | |
B -> 0 { B.val =0 } | |
B -> 1 { B.val =1 } | |
-} | |
bindec1 :: String -> Float | |
bindec1 xs = snd.s$xs | |
s :: String -> (String,Float) | |
s xs = let (xs0,_,val0)= (l xs 0) in | |
let (xs1,val1)=(f xs0 val0) in | |
( xs1 , val1 ) | |
f :: String -> Float -> (String,Float) | |
f ('.':xs) ival = let (xs0,_,val)= (l xs 1) in | |
(xs0,ival+val) | |
f xs val = (xs,val) {-ipsilon-} | |
l :: String -> Int -> (String,Int,Float) | |
l xs side = let (xs0,bit) = (b xs) in | |
let ival=case side of | |
0 -> bit | |
1 -> bit/2.0 in | |
(r xs0 side 1 ival) | |
r :: String -> Int->Int->Float -> (String,Int,Float) | |
r [] _ ik ival = ([],ik,ival) {-ipsilon-} | |
r xs@(bit:_) side ik ival | |
| bit=='0' || bit=='1' = | |
let (xs0,bval)= (b xs) in | |
let | |
ik0 =ik+1 | |
ival0=case side of | |
0 -> ival*2 + bval | |
1 -> ival + bval/(2^(ik+1)) in | |
(r xs0 side 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