Skip to content

Instantly share code, notes, and snippets.

@ytaras
Last active December 21, 2015 21:29
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 ytaras/6368427 to your computer and use it in GitHub Desktop.
Save ytaras/6368427 to your computer and use it in GitHub Desktop.
-- [x] Get input from user
-- [x] Do it only every two seconds
-- [x] Filter output < 3
-- [x] Send request to server
-- [x] Display results to user
import Graphics.Input as Input
import Maybe
import Http as H
import Json as J
import Time as T
-- Syntax
add : Int -> Int -> Int
add x y = y |> (+) x
|> (*) 2
divise : Float -> Float -> Maybe Float
divise x y = if y == 0 then Nothing else Just (x/y)
unsafeDivide : Float -> Float -> String
unsafeDivide x y = divise x y |> Maybe.maybe "Error" show
-- util
keepMaybe : (a -> Bool) -> Signal a -> Signal (Maybe a)
keepMaybe pred =
lift (\x -> if pred x then Just x else Nothing)
extractJsonString : J.JsonValue -> Maybe String
extractJsonString v =
case v of
J.String s -> Just s
_ -> Nothing
-- signals
(field, rawSearchTerm) = Input.field "Input your search text"
searchResult =
rawSearchTerm |> keepMaybe validTerm -- Signal Maybe String * filtered
|> sampleOn (every (2 * T.second)) -- Signal Maybe String * once in 2 secs
|> dropRepeats -- Signal Maybe String * without duplications
|> lift (Maybe.maybe "" searchUrl) -- Signal String * converted to URL
|> H.sendGet -- Signal Response String * response
|> lift extractSuggestions -- Signal [String] * results extracted
-- behaviour
searchUrl term =
"http://localhost:8080/wiki/w/api.php?format=json&action=opensearch&search=" ++ term
extractSuggestions : H.Response String -> [String]
extractSuggestions res = case res of
H.Success s -> s |> J.fromString |> \x -> justs [x] |> concatMap extractSuggestionsRaw
_ -> []
extractSuggestionsRaw : J.JsonValue -> [String]
extractSuggestionsRaw v = case v of
J.Array [_, J.Array arr] -> arr |> map extractJsonString |> justs
_ -> []
validTerm term = length term > 2
-- view
main = lift2 above field
(lift displayList searchResult)
displayList : [String] -> Element
displayList results =
results |> map (text . monospace . toText) -- [Element]
|> flow down -- Element
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment