简体   繁体   中英

“Type of many types” in Haskell

I'm totally new to functional programming and Haskell, so I am not sure I asked the question properly or if it makes sense, but I decided to try since I haven't found anything helpful. I'm basically trying to implement a function that can return an Int , a String , or a List. I know I can use Either to return one of two types, but I want to return one of three or more. I tried defining a new type, but I got stuck.

data Rets = Int | String | Bool

checkInt :: Rets -> Bool
check x = case x of
    Int x -> True

checkInt should return True if given an Int , it is just for testing but I included it anyway.

I'm aware that my question is a mess, so I would be thankful for any kind of explanation. Thanks in advance!

You defined a type with three constructors that each take 0 arguments. So Int x wouldn't be a valid pattern for your type, it would just be Int -> true . Of course this also means that you can't store any values in your type, so it doesn't do what you want it to.

What you want is something like this:

data Rets = IntRet Int | StringRet String | BoolRet Bool

This defines three constructors named IntRet , StringRet and BoolRet , which take an Int , String and Bool respectively. This way you can construct values using IntRet 42 , BoolRet True etc. and then pattern match them as IntRet x and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM