Currently I am using compose from a library called arrow which has it defined this way.
inline infix fun <IP, R, P1> ((IP) -> R).compose(crossinline f: (P1) -> IP): (P1) -> R = { p1: P1 -> this(f(p1)) }
What I am trying to do is compose functions from a list so I assumed something as simple as this would work.
val add5 = { i: Int -> Option(i + 5) }
val multiplyBy2 = { i: Int -> i * 2 }
fun isOdd(x: Option<Int>) = x.map { y -> y % 2 != 0 }
val composed = listOf(::isOdd, add5, multiplyBy2).reduce { a, b -> a compose b }
but I get type error:
Type inference failed: Cannot infer type parameter IP in inline infix
fun ((IP) -> R).compose(crossinline f: (P1) -> IP): (P1)
-> R None of the following substitutions receiver: (Any) -> Any arguments: ((Nothing) -> Any) receiver: (Nothing) -> Any arguments:
((Nothing) -> Nothing) can be applied to receiver: Function1<, Any>
arguments: (Function1<, Any>)
so I try:
val composed = listOf<(Any) -> Any>(::isOdd, add5, multiplyBy2).reduce { x, y -> x compose y }
and I get this:
Type mismatch: inferred type is KFunction1<#ParameterName Option, Option> but (Any) -> Any was expected
Type mismatch: inferred type is (Int) -> Option but (Any) -> Any was expected
Type mismatch: inferred type is (Int) -> Int but (Any) -> Any was expected
Any help appreciated. I don't mind if I end up having to write my own version of compose. I just need to be able to compose a list of functions.
edit:
This works no problems:
val composed = ::isOdd compose add5 compose multiplyBy2
I am just trying to achieve the same result should I have a list of functions instead of writing this way.
I find it hard to imagine how a simple compose should work with methods having so different signatures. So first we would have to align the types of the functions. Arrow let's you compose functions if the return type of the first matches the parameter of the second...
Another problem is that isOdd is a Predicate. It is not transforming a value.
If the transformers have a compatible signature you can compose them with e.g. andThen
Here is a version that aligns the types to compose the functions. Note that filter and map are special functions in arrow's Option that allow you to pass transformer functions/predicates
import arrow.core.Option
import arrow.core.andThen
import org.hamcrest.Matchers.`is`
import org.junit.Assert.assertThat
import org.junit.Test
class ComposeTest {
#Test
fun shouldCompose() {
val add5 = { i: Int -> i + 5 }
val multiplyBy2 = { i: Int -> i * 2 }
val isOdd = { x: Int -> x % 2 != 0 }
val composed: (Int) -> Option<Int> = { i: Int -> Option.just(i)
.filter(isOdd)
.map(add5.andThen(multiplyBy2))
}
assertThat(composed(3), `is`(Option.just(16)))
assertThat(composed(4), `is`(Option.empty()))
}
}
As pictured here, I've created a small sample program that has some controls to modify parts of the model.
What I've been unsuccessfully trying to do is to make a HTTP request to get the initial data (it's hardcoded right now), or later on replace the data with the response from said HTTP request when a Reset message is received. I did read the HTTP chaper of the introduction to Elm, but I can't seem to piece things together.
The goal is to have a loadTraits function that takes a String (SomeId) and returns a List of type TraitWithRelevance, so I can replace the model with that incoming data.
module Main exposing (..)
import Html exposing (Html, button, div, text, input, ul, img)
import Html.Attributes as Attr
import Html.Events exposing (onClick, onInput)
import Http exposing (..)
import Json.Decode as Decode
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
-- MODEL
type alias ContentWithTraits =
{ someId : SomeId
, traits : List TraitWithRelevance
}
type alias MetaInfo =
{ name : String
, imageUrl : String
}
type alias Name =
String
type alias SomeId =
String
type alias Relevance =
String
type alias TraitWithRelevance =
( Name, SomeId, Relevance )
type TraitToAdd
= Nothing
| TraitWithRelevance
type alias Model =
{ contentWithTraits : ContentWithTraits
, metaInfo : MetaInfo
, traitToAdd : TraitToAdd
}
init : ( Model, Cmd Msg )
init =
( Model contentWithTraits { name = "content name", imageUrl = "http://weknowmemes.com/generator/uploads/generated/g1369409960206058073.jpg" } Nothing, Cmd.none )
contentWithTraits : ContentWithTraits
contentWithTraits =
{ someId = "some default id"
, traits =
[ ( "name for trait a", "a", "1" )
, ( "this is the name for trait b", "b", "50" )
]
}
-- UPDATE
type Msg
= EditTrait SomeId Relevance
| Reset
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
EditTrait someId relevance ->
let
_ =
Debug.log "model: " model
in
( replaceTraits model <| List.map (updateTrait ( someId, relevance ))
, Cmd.none
)
Reset ->
-- ( replaceTraits model <| loadTraits model.contentWithTraits.someId, Cmd.none )
{-
NOTE: I'm stuck here...
should make HTTP GET request, then replace the model.contentWithTraits.traits with the decoded JSON's traits field
-}
( model, Cmd.none )
replaceTraits : Model -> (List TraitWithRelevance -> List TraitWithRelevance) -> Model
replaceTraits model func =
{ model
| contentWithTraits =
{ someId = model.contentWithTraits.someId
, traits = func model.contentWithTraits.traits
}
}
updateTrait : ( SomeId, Relevance ) -> TraitWithRelevance -> TraitWithRelevance
updateTrait updatedTrait originalTrait =
let
( name, someId, _ ) =
originalTrait
( someIdVerification, newValue ) =
updatedTrait
_ =
Debug.log "updatedTrait: " updatedTrait
in
if someId == someIdVerification then
( name, someId, newValue )
else
originalTrait
-- VIEW
valueRange : String -> TraitWithRelevance -> Html Msg
valueRange typ trait =
let
( name, someId, relevance ) =
trait
in
input [ Attr.type_ typ, Attr.min <| toString 0, Attr.max <| toString 100, Attr.value relevance, Attr.step <| toString 1, onInput <| EditTrait someId ] []
traitView : TraitWithRelevance -> Html Msg
traitView trait =
let
( name, someId, relevance ) =
trait
in
div []
[ text someId
, valueRange "range" trait
, valueRange "number" trait
, text name
]
view : Model -> Html Msg
view model =
div []
[ text model.contentWithTraits.someId
, img [ Attr.src model.metaInfo.imageUrl, Attr.width 300 ] []
, ul [] (List.map traitView model.contentWithTraits.traits)
, button [ onClick Reset ] [ text "Reset" ]
]
Here's an example response from the http server. I've chosen this format, because I thought it'd map easiest to the elm model. I can easily change the response if there's a better way to consume this data in elm.
{"traits":[["name for trait a","a",1],["this is the name for trait b,"b",50]]}
P.S. Even though there's plenty of lines of code, please be aware that I tried to strip down the problem as much as possible, while keeping enough context.
You need to have a message which returns the data. Assuming it's a simple list of Traits:
type Msg
= EditTrait SomeId Relevance
| Reset
| OnFetchTraits (Result Http.Error (List Traits))
Then you need a command to send the request, something like
fetchTraits : Cmd Msg
fetchTraits =
Http.get "http://localhost:4000/traits" traitListDecoder
|> Http.send OnFetchTraits
and you need to implement traitListDecoder, to decode your JSON into the list that is returned in the msg.
Then instead of returning Cmd.none in your update function where you are stuck, you return fetchTraits. Elm will then make the request and you will get an OnFetchTraits msg passed into update. You need a separate case to handle this. You unpack the Result type and extract your data if the request was successful, or handle the error if not.
So basically you need to do two things, the reset button should call a command to get the traits. Then, in the update you have to handle the response from the command. After getting the Result back you can use it to update your model.
Here is an update to your code. I added a person to the model which gets updated when the user presses the reset button.
module Main exposing (..)
import Html exposing (Html, button, div, text, input, ul, img)
import Html.Attributes as Attr
import Html.Events exposing (onClick, onInput)
import Http exposing (..)
import Json.Decode exposing (Decoder, string)
import Json.Decode.Pipeline exposing (decode, required)
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
-- Commands
type alias Person =
{ name : String
, gender : String
}
decodePerson : Decoder Person
decodePerson =
decode Person
|> required "name" string
|> required "gender" string
getTraits =
let
url =
"http://swapi.co/api/people/1/"
request =
Http.get url decodePerson
in
Http.send GetTraitResponse request
-- MODEL
type alias ContentWithTraits =
{ someId : SomeId
, traits : List TraitWithRelevance
}
type alias MetaInfo =
{ name : String
, imageUrl : String
}
type alias Name =
String
type alias SomeId =
String
type alias Relevance =
String
type alias TraitWithRelevance =
( Name, SomeId, Relevance )
type TraitToAdd
= Nothing
| TraitWithRelevance
type alias Model =
{ contentWithTraits : ContentWithTraits
, metaInfo : MetaInfo
, traitToAdd : TraitToAdd
, person : Person
}
init : ( Model, Cmd Msg )
init =
( Model contentWithTraits { name = "content name", imageUrl = "http://weknowmemes.com/generator/uploads/generated/g1369409960206058073.jpg"} Nothing {name = "", gender=""}, Cmd.none )
contentWithTraits : ContentWithTraits
contentWithTraits =
{ someId = "some default id"
, traits =
[ ( "name for trait a", "a", "1" )
, ( "this is the name for trait b", "b", "50" )
]
}
-- UPDATE
type Msg
= EditTrait SomeId Relevance
| GetTraitResponse (Result Http.Error Person)
| Reset
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
EditTrait someId relevance ->
let
_ =
Debug.log "model: " model
in
( replaceTraits model <| List.map (updateTrait ( someId, relevance ))
, Cmd.none
)
-- handle the response
GetTraitResponse resp ->
let
_ =
Debug.log "response" resp
person =
case resp of
Ok val ->
val
Result.Err e ->
{name = "", gender=""}
in
( {model | person = person }, Cmd.none )
Reset ->
-- ( replaceTraits model <| loadTraits model.contentWithTraits.someId, Cmd.none )
{-
NOTE: I'm stuck here...
should make HTTP GET request, then replace the model.contentWithTraits.traits with the decoded JSON's traits field
-}
-- call the command to get the traits
( model, getTraits )
replaceTraits : Model -> (List TraitWithRelevance -> List TraitWithRelevance) -> Model
replaceTraits model func =
{ model
| contentWithTraits =
{ someId = model.contentWithTraits.someId
, traits = func model.contentWithTraits.traits
}
}
updateTrait : ( SomeId, Relevance ) -> TraitWithRelevance -> TraitWithRelevance
updateTrait updatedTrait originalTrait =
let
( name, someId, _ ) =
originalTrait
( someIdVerification, newValue ) =
updatedTrait
_ =
Debug.log "updatedTrait: " updatedTrait
in
if someId == someIdVerification then
( name, someId, newValue )
else
originalTrait
-- VIEW
valueRange : String -> TraitWithRelevance -> Html Msg
valueRange typ trait =
let
( name, someId, relevance ) =
trait
in
input [ Attr.type_ typ, Attr.min <| toString 0, Attr.max <| toString 100, Attr.value relevance, Attr.step <| toString 1, onInput <| EditTrait someId ] []
traitView : TraitWithRelevance -> Html Msg
traitView trait =
let
( name, someId, relevance ) =
trait
in
div []
[ text someId
, valueRange "range" trait
, valueRange "number" trait
, text name
]
view : Model -> Html Msg
view model =
div []
[ text model.contentWithTraits.someId
, img [ Attr.src model.metaInfo.imageUrl, Attr.width 300 ] []
, ul [] (List.map traitView model.contentWithTraits.traits)
, button [ onClick Reset ] [ text "Reset" ]
, text <| toString model
]
While both answers have been correct and helpful, it took me still another mile to reach my destination.
First off, I didn't want to rely on a non elm-lang package.
Json.Decode.Pipeline therefore doesn't meet that requirement.
With the examples posted, I still had the trouble of decoding the list of traits. What I ended up doing was changing the response from the server so that the traits list is not of type list, but of type object with name, someId, and relevance as keys and its values as strings. This helped me distinguish between what's coming back from the server and what's being represented internally in my elm model.
So the Reset functionality works nicely, the next step is to get those values into the initial state of the model without user interaction.
module Main exposing (..)
import Html exposing (Html, button, div, text, input, ul, img)
import Html.Attributes as Attr
import Html.Events exposing (onClick, onInput)
import Http exposing (..)
import Json.Decode as Decode exposing (Decoder)
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
-- MODEL
type alias ContentWithTraits =
{ someId : SomeId
, traits : List TraitWithRelevance
}
type alias MetaInfo =
{ name : String
, imageUrl : String
}
type alias Name =
String
type alias SomeId =
String
type alias Relevance =
String
type alias TraitWithRelevance =
( Name, SomeId, Relevance )
type TraitToAdd
= Nothing
| TraitWithRelevance
type alias Model =
{ contentWithTraits : ContentWithTraits
, metaInfo : MetaInfo
, traitToAdd : TraitToAdd
}
type alias TraitInfo =
{ traits :
List TraitObject
}
type Traits
= TraitInfoFromServer (List TraitObject)
type alias TraitObject =
{ name : String, someId : String, relevance : String }
fetchTraits : String -> Cmd Msg
fetchTraits someId =
Http.get
("http://localhost:8000/traits/" ++ someId)
decodeTraits
|> Http.send OnFetchTraits
decodeTraits : Decoder TraitInfo
decodeTraits =
Decode.map TraitInfo
(Decode.field "traits" (Decode.list decodeTrait))
decodeTrait : Decoder TraitObject
decodeTrait =
(Decode.map3 TraitObject
(Decode.field "name" Decode.string)
(Decode.field "someId" Decode.string)
(Decode.field "relevance" Decode.string)
)
init : ( Model, Cmd Msg )
init =
( Model contentWithTraits { name = "content name", imageUrl = "http://weknowmemes.com/generator/uploads/generated/g1369409960206058073.jpg" } Nothing, Cmd.none )
contentWithTraits : ContentWithTraits
contentWithTraits =
{ someId = "someIdToStartWith"
, traits =
[ ( "trait a", "a", "1" )
, ( "trait b", "b", "50" )
]
}
-- UPDATE
type Msg
= EditTrait SomeId Relevance
| Reset
| OnFetchTraits (Result Http.Error TraitInfo)
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
EditTrait someId relevance ->
( replaceTraits model <| List.map (updateTrait ( someId, relevance ))
, Cmd.none
)
Reset ->
( model, fetchTraits model.contentWithTraits.someId )
OnFetchTraits resp ->
let
newTraits =
case resp of
Ok val ->
val.traits
Result.Err e ->
[]
in
( { model
| contentWithTraits =
{ someId = model.contentWithTraits.someId
, traits = List.map traitObjToTuple newTraits
}
}
, Cmd.none
)
traitObjToTuple : TraitObject -> TraitWithRelevance
traitObjToTuple obj =
( obj.name, obj.someId, obj.relevance )
replaceTraits : Model -> (List TraitWithRelevance -> List TraitWithRelevance) -> Model
replaceTraits model func =
{ model
| contentWithTraits =
{ someId = model.contentWithTraits.someId
, traits = func model.contentWithTraits.traits
}
}
updateTrait : ( SomeId, Relevance ) -> TraitWithRelevance -> TraitWithRelevance
updateTrait updatedTrait originalTrait =
let
( name, someId, _ ) =
originalTrait
( someIdVerification, newValue ) =
updatedTrait
in
if someId == someIdVerification then
( name, someId, newValue )
else
originalTrait
-- VIEW
valueRange : String -> TraitWithRelevance -> Html Msg
valueRange typ trait =
let
( name, someId, relevance ) =
trait
in
input [ Attr.type_ typ, Attr.min <| toString 0, Attr.max <| toString 100, Attr.value relevance, Attr.step <| toString 1, onInput <| EditTrait someId ] []
traitView : TraitWithRelevance -> Html Msg
traitView trait =
let
( name, someId, relevance ) =
trait
in
div []
[ text name
, valueRange "range" trait
, valueRange "number" trait
, text someId
]
view : Model -> Html Msg
view model =
div []
[ text model.contentWithTraits.someId
, img [ Attr.src model.metaInfo.imageUrl, Attr.width 100 ] []
, ul [] (List.map traitView model.contentWithTraits.traits)
, button [ onClick Reset ] [ text "Reset" ]
]
I am trying to mock the awscala.dynamodbv2.DynamoDB.putConditionalMethod
How would one define an expects for a method which is curried and includes a repeated parameter:
putConditional(tableName: String, attributes: (String, Any)*)(cond: Seq[(String, aws.model.ExpectedAttributeValue)]): Unit
Here's what I've got working:
(mockClient.putConditional(_: String, _: (String, Any))(_: Seq[(String, ExpectedAttributeValue)]))
.expects("Data-Identity-Partitions",
*,
Seq(
"DatacenterId" -> exp.isNull,
"InstanceId" -> exp.isNull,
"TTL" -> exp.isNull
))
But this:
(mockClient.putConditional(_: String, _: (String, Any))(_: Seq[(String, ExpectedAttributeValue)]))
.expects("Data-Identity-Partitions",
Seq("DatacenterId" -> 1,
"InstanceId" -> 0,
"TTL" -> System.currentTimeMillis()),
Seq(
"DatacenterId" -> exp.isNull,
"InstanceId" -> exp.isNull,
"TTL" -> exp.isNull
))
results in the following compiler error:
[error] AwsPartitionActorSpec.scala:76: type mismatch;
[error] found : Seq[(String, Any)]
[error] required: org.scalamock.matchers.MockParameter[(String, Any)]
[error] Seq[(String, Any)]("DatacenterId" -> 1,
[error] ^
better late than never i suppose, here's my suggestion:
trait testtrait {
def foo(t: String, a: (String, Any) *): Int
}
"foo" should "work" in {
val m = mock[testtrait]
m.foo _ expects where {
case ("foo", Seq(("bar", 42L), ("baz", "mango"))) => true
case _ => false
} returns 5
m.foo("foo", ("bar", 42L), ("baz", "mango")) should be (5)
}
If I have a string that looks like the name of a field in a record, can I use it to get the data somehow? Something like :
."name".toKey bill
bill.(asSymbol "name")
-
song =
{ title = "foot", artist = "barf", number = "13" }
fieldsILike : List String
fieldsILike =
[ "title", "artist" ]
val song key =
.key song
foo = List.map (val song) fieldsILike --> should be ["foot", "barf"]
No, but you could use a Dict
import Dict exposing (get ,fromList)
song = fromList [ ("title", "foot"), ("artist", "barf") ]
get "title" song -- Just "foot"
get "artist" song -- Just "barf"
get "test" song -- Nothing
Not the way you want it but you can have a function that pattern matches on a string to access a part of a record. You need to be explicit about what it should do in case you give it something invalid.
import Html exposing (..)
type alias Song = { artist : String, number : String, title : String }
song : Song
song =
{ title = "foot", artist = "barf", number = "13" }
fieldsILike : List String
fieldsILike =
[ "title", "artist" ]
k2acc : String -> (Song -> String)
k2acc key =
case key of
"title" -> .title
"artist" -> .artist
"number" -> .number
_ -> always ""
val : Song -> String -> String
val = flip k2acc
-- `flip` was removed in elm 0.19, so you'll need to
-- do something like the following going forward:
-- val song field = (k2acc field) song
foo = List.map (val song) fieldsILike
main = text <| toString foo
I solved this broblem by adding attribute's name and explicit type declaration in AttrValue type:
type alias TypedRecord =
List Attr
type alias Attr =
( String, AttrValue )
type AttrValue
= String String
| Int Int
| Record (List Attr)
So now i can retrieve attributes by "key" (even "key.key" for nested) from my TypedRecord type:
getAttrByKey : String -> TypedRecord -> Maybe Attr
getAttrByKey searchKey item =
-- imitation of searching for attributes likewise in JS Record
let
checkAttrKey =
\k attr ->
first attr == k
in
case String.split "." searchKey of
[ key ] ->
List.head <| List.filter (checkAttrKey key) item
key :: rest ->
case List.head <| List.filter (checkAttrKey key) item of
Just attr ->
case attr of
( _, Record subAttr ) ->
getAttrByKey (String.join "." rest) subAttr
( _, _ ) ->
Nothing
Nothing ->
Nothing
[] ->
Nothing
And conver it to String by checking Attr type and calling respected Elm String module function:
attrToString : Maybe Attr -> String
attrToString is_attr =
case is_attr of
Nothing ->
""
Just attr ->
case second attr of
String value ->
value
Int value ->
String.fromInt value
Record attrs ->
List.map (\a -> Just a) attrs
|> List.map (\a -> attrToString a)
|> String.join " "
These examples for String Int and Record Elm types, but it is also can be extended fo Float Bool and Array.
You can check src/lib/TypedRecord.elm file for another functions and even Json Decoder in my example app repository