Search code examples
functional-programmingsmlml

Function Declaration in SML?


The following is one way to declare a function I guess(correct me) & I want to do something similar using same style but it's not working, why?

fun length nil = 0
| length (_::l') = 1 + (length l')

I want to do this without using "case expression of" syntax. i.e if function x get a number 3 then return 0 else if it's 4 then 1

fun x 3 = 0
| x (4) = 1

Here's the error
stdIn:58.5-59.12 Warning: match nonexhaustive
    3 => ...
    4 => ...

Q2) Also, where does the body of function start? it looks like nil is a parameter but then we have | so i'm confused!


Solution

  • It's a definition with pattern matching, and it means the same as

    fun length ls = case ls of
                        nil => 0
                      | _::l' => 1 + (length l')
    

    but is more concise and readable.

    You get a warning on your function because you're only matching 3 and 4 but no other integers.

    You will get the same warning if you write

    fun x n = case n of
                  3 => 0
                | 4 => 1
    

    Matching all possible values would get rid of the warning:

    fun x 3 = 0
      | x 4 = 1
      | x _ = 2