Re: Type Checking
- Posted by "Carl W." <euphoria at cyreksoft.yorks.com> Oct 16, 2002
- 367 views
<mistertrik at hotmail.com> wrote: > A strange thing.... > > The code: > > object s > s = "" > ? sequence(s) > ? atom(s) > > outputs this: > > 1 > 0 > > Whereas this code: > > type pos(sequence x) > return length(x) = 2 and atom(x[1]) and atom(x[2]) > end type > > object t > > t = {} > ? pos(t) > > t = {43,70} > ? pos(t) > > t = -1 > ? pos(t) > > outputs this: > > 0 > 1 > ERROR: <Insert Crash and Burn here><Out of Cheese Error> ...etc > > The type crashes because the type passed to it did not fit the parameter > declaration. > I know I could have amended it to this: > > type pos(object x) > return sequence(x) and length(x) = 2 and atom(x[1]) and atom(x[2]) > end type > > but I shouldn't have to do that. I agree. You'll find that your amendment doesn't work either because returns in types aren't short-circuited. IIRC, Rob said he'd look at that for the next release of Euphoria. At the moment, I lay types out something like this: --- [global] type {name}(object {objectname}) if {TYPE}({objectname}) 1st constraint on {objectname} and 2nd constraint on {objectname} and : last constraint on {objectname} -- no 'and' on the last constraint! then return 1 end if return 0 end type -- this line never needs to change --- ... Where {TYPE} is a parent type of the type we're defining. Usually a sequence for advanced data types, but the programmer might want to put one of their own types there to create sub-types. The layout has the advantages of having the constraints at the beginning of a line, the true type of the user-type on the declaration line (since we can't put it into the real declaration), and the short circuiting of 'if' all rolled into one. The pos() type would then look like this: --- type pos(object x) if sequence(x) and length(x) = 2 and atom(x[1]) and atom(x[2]) then return 1 end if return 0 end type --- We can read this almost in English [I'm not sure how well this translates to other languages/grammars ;) ]: The new TYPE POS (referenced by X) is derived from a SEQUENCE where the LENGTH is 2 AND it has an ATOMic 1st element AND it has an ATOMic 2nd element. [The last line simply brings closure to the Euphoria syntax.] Make exceptions to the layout when it makes sense; This is the internal hour_() type from datetime.e: --- type hour_(object h) if integer(h) and 0 <= h and h <= 23 then return 1 end if return 0 end type --- Notice that in this case, the two constraints have been combined to make the line look more like the math statement "0 <= h <= 23". HTH, Carl