Search code examples
listsmlmlmosml

SML: What would be the best way to go through a list to take every other value?


I've been doing a lot of practice recently in sml and one problem I've found in my textbook was asking to create a function that applies a function to the odd indexed values in a list. When trying to solve this I don't really understand how to get every other value. for instance

fun something f [] = 0
    | something f (x:xs) = 

Here above I know that we can get the values in order via the x value but is there a way to now apply this to get only odd indexed values? Sorry if this is a simple question sml has been an interesting but confusing language.


Solution

  • You can "destructure" the list with pattern matching in that case too – patterns can be arbitrarily complex.
    For instance, a::b::bs matches a list with at least two elements, a::b::c::bs at least three, and so on.

    If we index the first element 1:

    fun everyOther _ [] = []
      | everyOther f [x] = [f x]
      | everyOther f (x::y::xs) = (f x)::y::(everyOther f xs)
    

    Test:

    val everyOther = fn : ('a -> 'a) -> 'a list -> 'a list
    val it = () : unit
    - fun square x = x * x;
    val square = fn : int -> int
    - everyOther square [1,2,3,4];
    val it = [1,2,9,4] : int list
    - everyOther square [1,2,3,4,5];
    val it = [1,2,9,4,25] : int list
    

    The case of the first element being indexed 0 rather than 1 left as an exercise.