Knaas
Knaas

Reputation: 11

SML in list parameter functions

I had two parameters. The first one was list, and the other was integer n. Our function formed a new list which contained the first n elements of the parameter list and suppose that n

([1,2,3,4],2 )  
  [1,2] 

How do I do that only using -> nil, ::, @ ?

Upvotes: 1

Views: 2819

Answers (1)

pad
pad

Reputation: 41290

What you describe is List.take function in SML basis library:

List.take ([1,2,3,4],2 )
[1,2]

If you want to make the function yourself:

fun take ([], _) = []
  | take (_, 0)  = []
  | take (x::xs, n) = x::take(xs, n-1)

Or to demonstrate the use of -> nil, ::, @ (the use of @ is not recommended, just for illustration purpose):

fun take (nil, _) = nil
  | take (_, 0)  = nil
  | take (x::xs, n) = [x] @ take(xs, n-1)

Upvotes: 1

Related Questions