Skip to content

Instantly share code, notes, and snippets.

@jah2488
Last active March 21, 2017 16:38
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 jah2488/cae274fa4d576867624dca2e0d94cbe3 to your computer and use it in GitHub Desktop.
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.
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" ] ) ] ]
]
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