RosettaCodeData/Task/Logical-operations/Icon/logical-operations-1.icon

63 lines
1.9 KiB
Plaintext

invocable all
procedure main() #: sample demonstrating boolean function use
limit := 4
char2 := char(2)||char(0)
every (i := char(1 to limit)|char2) do {
write(iop := "bnot","( ",image(i)," ) = ",image(iop(i)))
every k := 3 | 10 do {
write("bistrue(",image(i),",",k,") - ", if bistrue(i,k) then "returns" else "fails")
write("bisfalse(",image(i),",",k,") - ", if bisfalse(i,k) then "returns" else "fails")
}
every (j := char(1 to limit)) & (iop := "bor"|"band"|"bxor") do
write(iop,"( ",image(i),", ",image(j)," ) = ",image(iop(i,j)))
}
end
procedure bisfalse(b,p) #: test if bit p (numbered right to left from 1) is false; return b or fails
return boolean_testbit(0,b,p)
end
procedure bistrue(b,p) #: test if bit p is true; return b or fails
return boolean_testbit(1,b,p)
end
procedure bnot(b) #: logical complement of b (not is a reserved word)
static cs,sc
initial sc := reverse(cs := string(&cset))
if type(b) ~== "string" then runerr(103,b)
return map(b,cs,sc) # en-mass inversion through remapping ordered cset
end
procedure bor(b1,b2) #: logical or
return boolean_op(ior,b1,b2)
end
procedure band(b1,b2) #: logical or
return boolean_op(iand,b1,b2)
end
procedure bxor(b1,b2) #: logical or
return boolean_op(ixor,b1,b2)
end
procedure boolean_testbit(v,b,p) #: (internal) test if bit p is true/false; return b or fail
if not 0 <= integer(p) = p then runerr(101,p)
if type(b) ~== "string" then runerr(103,b)
if v = ishift(ord(b[-p/8-1]), -(p%8)+1) then return b
end
procedure boolean_op(iop,b1,b2) #: boolean helper
local b3,i
static z
initial z := char(0)
if type(b1) ~== "string" then runerr(103,b1)
if type(b2) ~== "string" then runerr(103,b2)
b3 := ""
every i := -1 to -max(*b1,*b2) by -1 do
b3 := char(iop(ord(b1[i]|z),ord(b2[i]|z))) || b3
return b3
end