Type Inference in Haskell v. Scala -


given following code:

prelude> let f x = if (x) 55 else "foo" 

why compiler num [char]?

<interactive>:2:23:     no instance (num [char]) arising literal `55'     in expression: 55     in expression: if (x) 55 else "foo"     in equation `f': f x = if (x) 55 else "foo" 

however, in scala, find least-upper bound of 55 , "foo", any:

scala> def f(x: boolean) = if (x) 55 else "foo" f: (x: boolean)any  import scala.reflect.runtime.universe._  scala> lub( list[type]( typeof[int], typeof[string] ) ) res4: reflect.runtime.universe.type = 

what's key difference between haskell's , scala's type inference?

you can add instance num [char] in haskell, if that's want:

{-# language flexibleinstances #-}  import data.function (on) import data.composition ((.:))  -- cabal install composition  helper :: (integer -> integer -> integer) -> (string -> string -> string) helper op = show .: on op read  cast :: (integer -> integer) -> (string -> string) cast f = show . f . read  instance num [char]     frominteger = show     (+) = helper (+)     (-) = helper (-)     (*) = helper (*)     abs = cast abs     signum = cast signum     negate = cast negate 

where 1 possible implementation. make example compile:

> let f x = if x 55 else "foo" > f true "55" > f false "foo" 

haskell has polymorphic numeric literals, 55 :: num => a, , since both branches of if must return same type, forcing a ~ [char] having else branch return "foo". leads confusing error message, can powerful feature. means numeric literal can act type need be, , it's same concept behind overloadedstrings extension, allowing have polymorphic string literals instead of using pack everywhere need text or bytestring.

scala uses subtyping , has generic type values. allows relax type safety on function , return literally anything. haskell not have subtyping @ all, way unify types (similar finding lub) use fact numeric literals polymorphic under num constraint, in order compile "foo" has implement num. actually, if enabled overloadedstrings f compile fine type

f :: (data.string.isstring a, num a) => bool -> 

there aren't types default meet both constraints, ghc happily accept valid function.


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -