Last active
March 21, 2017 16:38
-
-
Save jah2488/cae274fa4d576867624dca2e0d94cbe3 to your computer and use it in GitHub Desktop.
Do now for Tuesday the 21st of March. Converting a string into a dictionary by last names.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main exposing (..) | |
import Html exposing (Html, div, text) | |
import Dict exposing (Dict) | |
names : String -> Dict String (List String) | |
names str = | |
str | |
|> String.split ", " | |
|> List.map (\name -> String.split " " name) | |
|> List.foldl insertNames Dict.empty | |
insertNames : List String -> Dict String (List String) -> Dict String (List String) | |
insertNames names dict = | |
Dict.update (names |> List.reverse |> first) (addOrUpdate (first names)) dict | |
addOrUpdate : String -> Maybe (List String) -> Maybe (List String) | |
addOrUpdate str value = | |
case value of | |
Just n -> | |
Just (str :: n) | |
Nothing -> | |
Just [ str ] | |
first : List String -> String | |
first list = | |
list | |
|> List.head | |
|> Maybe.withDefault "Not Given" | |
main : Html a | |
main = | |
let | |
foo = (names "George Washington, Adam West, Kanye West") | |
in | |
div [] | |
[ (text <| toString foo) | |
, div [] [ text <| toString <| foo == Dict.fromList [ ( "Washington", [ "George" ] ), ( "West", [ "Kanye", "Adam" ] ) ] ] | |
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def names(str) | |
Hash[str | |
.split(", ") | |
.map { |full_names| full_names.split(" ") } | |
.group_by { |(first, last)| last } | |
.map { |(last_name, full_names)| [last_name, full_names.map(&:first)] }] | |
end | |
expected = { "West" => ["Kanye", "Adam"], "Washington" => ["George"] } | |
actual = names("George Washington, Kanye West, Adam West") | |
puts expected | |
puts actual | |
puts expected == actual |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment