MUST BE WRITTEN IN ELM The List library function includes a take such that take
ID: 3877622 • Letter: M
Question
MUST BE WRITTEN IN ELM
The List library function includes a take such that take k xs returns the first k elements of xs. If k is negative or if there are not enough elements in xs, take quietly succeeds anyway. In this problem, you will write a version of take that differentiates between the success and error cases using the Result type Implement the function take Int -> List a -> Result String (List a) so that it returns the error strings "not enough elements" and "negative index" in the corresponding error cases. For example: > take 0 (List.range 1 9) Ok [1: Result.Result String (List Int) > take 5 (List.range 1 9) Ok [1,2,3,4,51: Result.Result String (List Int) > take 10 (List.range 1 9) Err "not enough elements": Result.Result String (List Int) > take (-10) (List.range 1 9) Err "negative index" Result.Result String (List Int)Explanation / Answer
take : Int -> List a -> Result String (List a)
take k xs =
if | k > List.length xs -> Err "not enough elements"
| k < 0 -> Err "negative index"
| otherwise -> Ok (List.take k xs)
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.