Skip to main content

tk3++

MyList実装 Head/Tail/Remove F#

dojo/fsharp/MyList/Program.fs at main · tk3/dojo

今日はHead/Tail/Removeを実装した。これまでの経験があればこそ比較的楽に書けた。 ただ、書けはしたものの、tryItemがちょっと怪しくて、removeAtは怪しい。体感では理解していても、きちんとした理解になっていない気がする。慣れるしかないのか。分かるようで分かっていない感じ。あーもどかしい。

let tryHead list =
    match list with
    | Empty -> None
    | Cons(x, _) -> Some x

let tryTail list =
    match list with
    | Empty -> None
    | Cons(_, tail) -> Some tail

let rec tryItem idx list =
    match list with
    | Empty -> None
    | Cons(x, tail) ->
        if idx = 0 then
            Some(x)
        else
            tryItem (idx - 1) tail

let rec removeAt idx list =
    match list with
    | Empty -> Empty
    | Cons(x, tail) ->
        if idx = 0 then
            tail
        else if idx < 0 then
            Cons(x, tail)
        else
            Cons(x, removeAt (idx - 1) tail)