Skip to content

Instantly share code, notes, and snippets.

@CraZySacX
Created April 30, 2014 16: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 CraZySacX/e965decfd846fc6a8a17 to your computer and use it in GitHub Desktop.
Save CraZySacX/e965decfd846fc6a8a17 to your computer and use it in GitHub Desktop.
Clojure to Haskell
(defn- target
"generate a target from a user and host string.
If user and host are nil, evaluates to localhost.
If host is nil, evaluates to user@localhost.
If user is nil, evaluates to host.
Otherwise evaluates to user@host."
[user host]
(let [host (if (string? host) host "localhost")
user (if (string? user) (str user "@") "")]
(str user host)))
target :: String -> String -> String
target user host = user ++ "@" ++ host
{- How do I do the cases where host and user are not supplied?
My hunch is new functions with less args, but maybe there
is a simpler way -}
targetNoHost :: String -> String
targetNoHost user = target user "localhost"
targetNoUser :: String -> String
targetNoUser host = host
@ckirkendall
Copy link

you nee a Maybe instead of a string.

target :: Maybe String -> Maybe String -> String
target :: Nothing Nothing = "localhost"
target :: Nothing Just(host) = host
target :: Just(user) Nothing = "localhost@" ++ user
target :: Just(user) Just(host) = host ++ "@" ++ user

@bkyrlach
Copy link

bkyrlach commented May 2, 2014

I think this solution gives the desired API.

data NameAndHost = Name String | Host String | Both String String deriving Show

buildHostString :: NameAndHost -> String
buildHostString (Name n)   = n ++ "@localhost"
buildHostString (Host h) = "anonymous@" ++ h
buildHostString (Both n h) = n ++ "@" ++ h

This code snippet can be used as such...

*Main> buildHostString $ Name "ben"
"ben@localhost"
*Main> buildHostString $ Host "google.com"
"anonymous@google.com"
*Main> buildHostString $ Both "ben" "google.com"
"ben@google.com"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment