简体   繁体   中英

This expression has type int list but an expression was expected of type unit

I tried this in utop but since I am not familar with a dune project, it failed and report the error

This expression has type int list but an expression was expected of type unit.

This is for the line filter greaterthanfive list1

open Base

let rec filter p inputList = match inputList with
    [] -> []
    | x::xs -> if p x then x::filter p xs else filter p xs
;;

let greaterthanfive num =
  if num>5 then true else false;;

let () = 
    let list1 = [1;6;8;3] in
    filter greaterthanfive list1
;;

let () = <expr> means <expr> is expected to evaluate to ()

More generally, this construct has the form let <pattern> = <expr> , where <pattern> is anything you can put in the branch of a match expression. And () is a literal pattern that will only match this value, which is also the only value of the type unit .

In program code it is good practice to use let () = <expr> for the main part of the program to make sure it evaluates to () and indicates it will only have side-effects, such as printing to the terminal or writing to a file.

In utop however, you usually want the value of an expression to be sent to utop to be printed, and in that case let () = <expr> prevents that. Instead you should just evaluate the expression directly.

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