[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: another take on hackers and painters



Neel Krishnaswami writes: 

> John Clements writes:
>> 
>> Be careful.  The distinction you're talking about is largely
>> orthogonal to the dynamic vs. static typing issue.  Case in point:
>> Scheme is dynamically typed, but will not perform the coercion
>> you're describing. At the opposite corner, there's no reason you
>> can't have a statically typed language with coercion.
> 
> Haskell does this, and the way it does so is how I learned that
> automatic coercions and overloading are the same thing. Numeric
> literals like 123 aren't immediately interpreted as integers. Instead,
> it gets the type 'Num a => a', which says that this expression is some
> kind of number, and the specific kind it gets coerced to do depends on
> the context in which it is used. So writing 
> 
>   let x :: Float = 3 
> 
> won't cause a type error due to '3' being an integer and 'x' being a
> float, like it would in ML. Haskell isn't as free-spirited with its
> coercions as a language like Perl is, but that seems more a matter of
> differing design sensibility rather than technical feasibility to me. 
> 
> -- 
> Neel Krishnaswami
> neelk@alum.mit.edu

Hi, 

   Hmmm I believe Haskell can be like statically typed Perl. I hacked this 
to add (partial) support to automatic String->Int coercion. 


data Str = Str [Char] deriving (Eq, Show) 

apply1 f (Str x)         = Str $ show $ f (read x)
apply2 f (Str x) (Str y) = Str $ show $ f (read x) (read y) 

instance Num Str
   where
       (+) = apply2 (+)
       (*) = apply2 (*)
       negate = apply1 negate
       abs = apply1 abs
       signum = apply1 signum
       fromInteger x = Str (show x) 

fac 0 = 1
fac n = n * fac (n - 1) 

Hugs session for:
C:\Arquivos de programas\Hugs98\lib\Prelude.hs
C:\home\projetos\lambda\String.hs
Main> 123 + (Str "156" * 354) + 2 - Str "125"
Str "55224"
Main> 123 + (156 * 354) + 2 - 125
55224
Main> fac (Str "10")
Str "3628800"
Main> fac 10
3628800
Main> 


   Sure we could do better, I'm just a newbie in Haskell. Real coercion 
support would include other numeric type classes and support real String 
type (instead of this Str datatype). 

   Best regards,
   Daniel Yokomiso. 

"I hope that by having this open dialogue we can live in harmony. Or failing 
in that, I'll live in harmony by myself."
 - Dogbert