#nested case vs guards vs use with bool.guard

1 messages · Page 1 of 1 (latest)

sullen kernel
#

I am going through SICP (JavaScript version) and using Gleam to do the exercises . I wrote a solution to one of the exercises essentially using the same predicates in 3 different ways and was wondering if there is a preferred Gleam way?

/// Declare a function that takes three numbers as arguments and returns the sum
/// of the squares of the two larger numbers.
fn sum_sq_lrg1(a, b, c) {
  use <- guard(when: a < b && a < c, return: sum_of_squares(b, c))
  use <- guard(when: b < a && b < c, return: sum_of_squares(a, c))
  sum_of_squares(a, b)
}

fn sum_sq_lrg2(a, b, c) {
  case a, b, c {
    _, _, _ if a < b && a < c -> sum_of_squares(b, c)
    _, _, _ if b < a && b < c -> sum_of_squares(a, c)
    _, _, _ -> sum_of_squares(a, b)
  }
}

fn sum_sq_lrg3(a, b, c) {
  case a < b && a < c {
    True -> sum_of_squares(b, c)
    False -> {
      case b < a && b < c {
        True -> sum_of_squares(a, c)
        False -> sum_of_squares(a, b)
      }
    }
  }
}
wild rapids
#

I'd take your third one and rearrange it like this

fn sum_sq_lrg4(a, b, c) {
  case a < b && a < c, b < a && b < c {
    True, _ -> sum_of_squares(b, c)
    _, True -> sum_of_squares(a, c)
    _, _ -> sum_of_squares(a, b)
  }
}
crude lark
#

Less related to your question but more to the underlying problem: you can make a list [a, b, c] then sort it, drop the smallest element, list.map etc

sullen kernel