Skip to content

Instantly share code, notes, and snippets.

@charlieegan3
Last active April 22, 2016 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save charlieegan3/f5b1fb8c1b882d272ad5e5f896de87ac to your computer and use it in GitHub Desktop.
Save charlieegan3/f5b1fb8c1b882d272ad5e5f896de87ac to your computer and use it in GitHub Desktop.
Elm: 99 questions
-- q1: myLast
import Html exposing (text)
myLast : List a -> Result String a
myLast list =
Result.fromMaybe ("Can't get head of empty.")
<| List.head
<| List.reverse list
main =
case myLast [] of
Ok list -> text (toString list)
Err err -> text err
-- q2: myButLast
import Html exposing (text)
myButLast : List a -> Result String a
myButLast aList =
case aList of
[] -> Err "List is empty"
[_] -> Err "List is too short"
x -> Result.fromMaybe (toString x)
<| List.head
<| List.drop ((List.length x) - 2) x
main =
case myButLast [1, 3, 4] of
Ok list -> text (toString list)
Err err -> text err
-- q3: elementAt
import Html exposing (text)
elementAt : List a -> Int -> Result String a
elementAt aList i =
if i < 1 || i > List.length aList then
Err "Invalid Index"
else
case i of
1 -> Result.fromMaybe "Failed to get head" (List.head aList)
_ -> elementAt (List.drop 1 aList) (i - 1)
main =
case elementAt ["asdf", "qwer"] 2 of
Ok element -> text <| toString element
Err err -> text err
-- q4: myLength
import Html exposing (text)
myLength : List a -> Int
myLength aList =
case aList of
[] -> 0
[x] -> 1
x::xs -> 1 + myLength xs
main =
text <| toString <| myLength [1,2,3,4,5]
-- q5: myReverse
import Html exposing (text)
myReverse : List a -> List a
myReverse aList = List.foldl (::) [] aList
main =
text <| toString <| myReverse [1,2,3]
-- q6: myReverse
import Html exposing (text)
isPalindrome : List a -> Bool
isPalindrome aList = aList == List.reverse aList
main =
text <| toString <| isPalindrome [1,2,3,2,1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment