@@ -6,7 +6,10 @@ module Data.Argonaut.Decode.Class
66 ) where
77
88import Prelude
9-
9+ import Data.Array as Arr
10+ import Data.Map as M
11+ import Data.StrMap as SM
12+ import Control.Alternative (class Plus )
1013import Data.Argonaut.Core (Json , JArray , JObject , isNull , foldJsonNull , foldJsonBoolean , foldJsonNumber , foldJsonString , toArray , toNumber , toObject , toString , toBoolean )
1114import Data.Array (zipWithA )
1215import Data.Bifunctor (lmap )
@@ -15,13 +18,12 @@ import Data.Foldable (find)
1518import Data.Generic (class Generic , GenericSpine (..), GenericSignature (..), fromSpine , toSignature )
1619import Data.Int (fromNumber )
1720import Data.List (List (..), (:), fromFoldable )
18- import Data.Map as M
21+ import Data.List as L
1922import Data.Maybe (maybe , Maybe (..))
23+ import Data.NonEmpty (NonEmpty , singleton , (:|))
2024import Data.String (charAt , toChar )
21- import Data.StrMap as SM
2225import Data.Traversable (traverse , for )
2326import Data.Tuple (Tuple (..))
24-
2527import Type.Proxy (Proxy (..))
2628
2729class DecodeJson a where
@@ -110,6 +112,23 @@ instance decodeJsonString :: DecodeJson String where
110112instance decodeJsonJson :: DecodeJson Json where
111113 decodeJson = Right
112114
115+
116+ toNonEmpty :: forall a f . (Plus f ) => ({ head :: f a -> Maybe a , tail :: f a -> Maybe (f a ) } ) -> (f a ) -> Either String (NonEmpty f a )
117+ toNonEmpty i a = case (Tuple (i.head a) (i.tail a)) of
118+ (Tuple Nothing _) -> Left " is empty."
119+ (Tuple (Just h) Nothing ) -> Right $ singleton h
120+ (Tuple (Just h) (Just t)) -> Right $ h :| t
121+
122+ instance decodeJsonNonEmptyArray :: (DecodeJson a ) => DecodeJson (NonEmpty Array a ) where
123+ decodeJson
124+ = lmap (" Couldn't decode Array: " <> _)
125+ <<< (traverse decodeJson <=< (toNonEmpty { head : Arr .head, tail : Arr .tail } ) <=< decodeJArray)
126+
127+ instance decodeJsonNonEmptyList :: (DecodeJson a ) => DecodeJson (NonEmpty List a ) where
128+ decodeJson
129+ = lmap (" Couldn't decode NonEmpty List: " <> _)
130+ <<< (traverse decodeJson <=< (lmap (" List" <> _) <<< toNonEmpty { head : L .head, tail : L .tail }) <=< map (map fromFoldable) decodeJArray)
131+
113132instance decodeJsonChar :: DecodeJson Char where
114133 decodeJson j =
115134 maybe (Left $ " Expected character but found: " <> show j) Right
0 commit comments