Create a type that can contain int and string in any order

I follow this in Haskell , and this is a specific place (user-defined types 2.2). I am especially obscure. In fact, I don’t even understand which part of this code and which part are the author’s thoughts. (What is Pt- is it not defined anywhere?). Needless to say, I cannot execute / compile it.

As an example that would make it easier for me to understand, I would like to define a type that is a pair of Integer and String, or String and Integer, but nothing more.

The theoretical function that will use it will look like this:

combine :: StringIntPair -> String
combine a b = (show a) ++ b
combine a b = a ++ (show b)

If you need working code, then it does the same, here is the CL code for this:

(defgeneric combine (a b)
  (:documentation "Combines strings and integers"))

(defmethod combine ((a string) (b integer))
  (concatenate 'string a (write-to-string b)))

(defmethod combine ((a integer) (b string))
  (concatenate 'string (write-to-string a) b))

(combine 100 "500")
+4
source share
3

:

data StringIntPair = StringInt String Int | 
                     IntString Int String 
    deriving (Show, Eq, Ord)

, StringIntPair, StringInt IntString.

combine:

combine :: StringIntPair -> String
combine (StringInt s i) = s ++ (show i)
combine (IntString i s) = (show i) ++ s

.

:

*Main> let y = StringInt "abc" 123
*Main> let z = IntString 789 "a string"
*Main> combine y
"abc123"
*Main> combine z
"789a string"
*Main> :t y
y :: StringIntPair
*Main> :t z
z :: StringIntPair

, :

  • StringIntPair - ; :t <expression>
  • StringInt IntString
  • (|)
  • ; combine :
+8
data StringIntPair = StringInt String Int
                   | IntString Int String

combine :: StringIntPair -> String
combine (StringInt s i) = s ++ (show i)
combine (IntString i s) = (show i) ++ s

:

> combine $ StringInt "asdf" 3
"asdf3"
> combine $ IntString 4 "fasdf"
"4fasdf"
+7

Haskell , , . , . , length, . :

length :: [a] -> Int

, a ( ) Int. node , , , . Haskell , , Java, .

, (ADT). , String, Int, Int, String :

data StringIntPair = StringInt String Int
                   | IntString Int String

You can find out which of the two is taken by matching the samples by parameter. (Note that you only have one, as both the string and the string are encapsulated in ADT):

combine :: StringIntPair -> String
combine (StringInt str int) = str ++ show int
combine (IntString int str) = show int ++ str
+3
source

All Articles