SML / NJ - dynamic type template

Is it possible to write functions with dynamically typed input parameters? I tried pattern matching, but apparently this doesn't work.

I want to do something like this:

fun firstStr (0,n:string) = n
  | firstStr (b:string,n:string) = if b>n then n else b;

Thanks.

+3
source share
3 answers

StandardML is a strong, statically typed language. Therefore, you cannot have a function that takes an int in the first case and a string in the second. Mistake:

this clause:        string * string -> 'Z
previous clauses:      int * string -> 'Z
in declaration:
  firstStr =
    (fn (0,<pat> : string) => n
      | (<pat> : string,<pat> : string) => if <exp> > <exp> then n else b)

, , int, , tagged union "(aka" "), . :

datatype Wrapper = Int    of int
                 | String of string
fun firstStr(Int 0,    n:string) = n
  | firstStr(String b, n:string) = if b>n then n else b

, Wrapper, . , n ;

fun firstStr(Int 0,    n) = n
  | firstStr(String b, n) = if b>n then n else b

, , : , , ?

, , b>n, ? , SML, (-) . , ?

+10

, , , , , , , , , . ? string option ( option, SOME NONE http://www.standardml.org/Basis/option.html):

datatype string_or_int = String of string
                       | Int    of int 

fun firstStr(String a, String b) = SOME (if a < b then a else b)
  | firstStr(String a, Int _   ) = SOME a
  | firstStr(Int _,    String b) = SOME b
  | firstStr(Int _,    Int _   ) = NONE

firstStr

string_or_int * string_or_int -> string option

ML - . , , , , string option * string -> string, ; getOpt . , , string option * string -> string,

fun firstStr(SOME a, b) = if a < b then a else b
  | firstStr(NONE,   b) = b

SOME option .

+7

Polymorphic options in OCaml have more of the dynamic property you are looking for. You can see if you want, OCaml and SML are very close languages.

+1
source

Source: https://habr.com/ru/post/1724036/


All Articles