如果某些东西不是Haskell中的列表 [英] If Something Is Not A List In Haskell

查看:128
本文介绍了如果某些东西不是Haskell中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何检查Haskell中的对象是否不是列表?例如,我想知道如果

let a = 55 a 是列表还是只是一个数字?

解决方案

您不检查。你确实是这样做的。



但是,真的,你想在这里做什么?

如果你试图确保你的函数只能用列表来调用。

Haskell将确保你的函数只能用一个列表调用。如果您尝试使用非列表调用您的函数,这将导致编译错误。



例如

  myFunction :: [a]  - >字符串
myFunction [] =没有元素!
myFunction [_] =单个元素!
myFunction _ =很多元素!

然后

  myFunction [42]  - >>> 单一元素! 
myFunction 42 - 错误:不是列表



如果你想让你的函数做某事明智地知道它是用列表还是别的东西来调用的。



使用一个typeclass:当你用一个列表调用函数时写入不同版本的函数,用其他类型调用(在合理范围内);然后Haskell确保函数的正确版本被调用。

例如

  class MyClass a 
where myFunction :: a - >字符串

实例MyClass Int
其中myFunction 0 =零!
myFunction 1 =one!
myFunction _ =有东西!

实例MyClass a => MyClass [a]
where myFunction [] =no elements!
myFunction [x] =only++ myFunction x
myFunction _ =许多元素!

然后

  myFunction [42]  - >>> 只有东西! 
myFunction 42 - >>> 什么!

通常,函数的列表版本将要调用函数的非列表版本并合并结果在某种程度上。



哪种情况适合您的情况取决于您正在尝试做什么。如果一个类型类型是合适的,你可能可以重用一个标准类型类。


How do i check if an object in Haskell is not a list? for instance i want to know if
let a = 55, a is a list or just a number?

解决方案

You don't check. You do.

But really, what are you trying to do here?

If you are trying to ensure your function can only be called with a list

Haskell will make sure your function can only be called with a list. If you try to call your function with a non-list, this will cause a compile error.

e.g.

myFunction :: [a] -> String
myFunction []  = "no elements!"
myFunction [_] = "single element!"
myFunction _   = "many elements!"

then

myFunction [42] -- >>> "single element!"
myFunction 42   -- ERROR: not a list

If you want your function to do something sensible whether it is called with a list or with something else

Use a typeclass: write different versions of your function for when it is called with a list and for when it is called with other types (within reason); Haskell then ensures that the proper version of your function is called.

e.g.

class MyClass a
  where myFunction :: a -> String

instance MyClass Int
  where myFunction 0 = "zero!"
        myFunction 1 = "one!"
        myFunction _ = "something!"

instance MyClass a => MyClass [a]
  where myFunction []  = "no elements!"
        myFunction [x] = "only " ++ myFunction x
        myFunction _   = "many elements!"

then

myFunction [42] -- >>> "only something!"
myFunction 42   -- >>> "something!"

Often the list version of your function will want to call the non-list version of your function and combine the results in some way.

Which is appropriate in your situation depends on exactly what you're trying to do. If a typeclass is appropriate, you may be able to reuse a standard typeclass.

这篇关于如果某些东西不是Haskell中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆