DEV Community

Discussion on: No duplicates challenge in Elm

Collapse
josephthecoder profile image
Joseph Stevens

Haha,I like to think I know FP well, but, when I try to do recursive functions like this, my whole brain freezes up 😅

Collapse
1hko profile image
1hko • Edited on

It's all about mastering inductive reasoning.

someFunc n = 
    if n == 0 then
        -- do something when n IS zero (base case)
    else
        -- do something where n is (by inductive reasoning) NOT zero

Or

someFunc list =
    if List.isEmpty list then
        -- handle the empty list (base case)
    else
        -- the list (by inductive reasoning) has at least one element

Pattern matching streamlines this for us by allowing us to express the base case and any induction steps using a nice syntax

someFunc n =
    case n of
        0 ->  -- base case
        _ -> -- induction step

Or

someFunc list =
    case list of
        [] -> -- base case
        first :: more -> -- induction step